0

How can I invoke setVisible(false) of JFrame within addActionListener function of a JButton (like below) :

jButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent arg0) {
   //here           
  }
});
Adil
  • 4,503
  • 10
  • 46
  • 63
  • 1) Look into `JFrame.DISPOSE_ON_CLOSE` 2) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Nov 09 '12 at 00:10

2 Answers2

2

Supposing you have a variable declared like:

JFrame frame;

you just need to call:

frame.setVisible(false);

Otherwise, if you are inside a class that extends JFrame, you have to:

NameOfClass.this.setVisible(false);

Or even better that using setVisible(false), you ca dispose() it.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
2

You just need the frame accessible in the spot where your button's action is defined. You can do this by making the JFrame final, or by making it a field in the class where the Action is defined:

import java.awt.event.*;
import javax.swing.*;

public class CloseFrame extends JPanel{

    public CloseFrame(final JFrame frame){

        JButton button = new JButton("Hide Screen");
        button.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                //What you asked for:
                frame.setVisible(false);
                // What you should use instead of the above:
                //frame.dispose(); 
            }});

        add(button);
    }


    public static void main(String[] args){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new CloseFrame(frame));
        frame.pack();
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

EDIT

Also please note that you should probably use JFrame.dispose() if you really are trying to close the application.

Nick Rippe
  • 6,465
  • 14
  • 30
  • thanks, my situation is that I have a class that extends JFrame, so _Dan_ has the right answer (+1) – Adil Nov 08 '12 at 16:15