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
}
});
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
}
});
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.
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.