0
public class MyClass extends JFrame implements ActionListener {

 public MyClass() {
  super("Frame Window");
  setLayout(new FlowLayout());
  setSize(700, 500);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  JButton setInv = new JButton("set invisible");
  setInv.setVisible(true);
  setInv.setPreferredSize(new Dimension(50, 50));
  add(setInv);

 }

 public static void main(String[] args) {
  MyClass obj = new MyClass();
  obj.setVisible(true);

 }

 public void actionPerformed(ActionEvent e) {
  if (e.getActionCommand() == "set invisible") {


   // I want an Accessor method for the parent JFrame and then I want to  
   // set it invisible here!

  }
 }
}

A person suggested getParent() method, but it is not working as I want! getParent() returns some container in this case it is JFrame I think..

I have tried getParent().setInvisible(false); but nothing happens.. I know it is error in my logic or something but what should I do?

Java is flexible but full of exceptions at many points!

there is one thing that if I dont extend MyClass from JFrame and create a public instance of JFrame and then setVisible(false); can be called by its reference! but i do not want to do so...because i have made a project with a lot of classes and i do not want to change my code like this... any help guys!

Flown
  • 11,480
  • 3
  • 45
  • 62
  • 3
    Possible duplicate of [Get Any/All Active JFrames in Java Application?](https://stackoverflow.com/questions/7364535/get-any-all-active-jframes-in-java-application) – Arnaud Jun 13 '17 at 07:41
  • Also have a look at this : https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Arnaud Jun 13 '17 at 07:44
  • no use.. JFrame is not hiding or whatsoever! – Abdur Rehman Shahbaz Jun 13 '17 at 07:48
  • Welcome to SO. You can create a reference by `JFrame farme = this` or if used within the class you can simply use `this` – c0der Jun 13 '17 at 07:55

2 Answers2

0

You haven't added an ActionListener to your JButton. Also, you're not disposing or hiding your JFrame in your ActionListener.

As a side note: String is an Object. Use String::equals instead of ==.

public class MyClass extends JFrame implements ActionListener {

    public MyClass() {
        super("Frame Window");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton setInv = new JButton("set invisible");
        setInv.addActionListener(this);
        add(setInv);
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {
        if ("set invisible".equals(e.getActionCommand())) {
            dispose();
        }
    }
}
Flown
  • 11,480
  • 3
  • 45
  • 62
0

Simply

if (e.getActionCommand() == "set invisible") {
        setVisible(false); // or this.setVisible(false);
 }
c0der
  • 18,467
  • 6
  • 33
  • 65