Mahdi_Nine
Mahdi_Nine

Reputation: 14751

Problem with setVisible(boolean)

I have a JFrame with some component on it. I want that the frame disappears when i click on a special button for example exit button.

I wrote this code in exit button

this.setvisible(false);

but it only hides the component on it and frame doesn't disappear.

What can I do that when I click on exit button the frame disappears?

Upvotes: 0

Views: 4114

Answers (3)

Suhail Gupta
Suhail Gupta

Reputation: 23216

call it on JFrame object. example: // when exit is pressed

fr.setVisible(false); // fr is a reference to object of type JFrame `

Upvotes: 0

Aleksi Yrttiaho
Aleksi Yrttiaho

Reputation: 8446

Here's an example of a button that hides the frame:

final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JButton hideButton = new JButton("hide frame");
frame.add(hideButton);
hideButton.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {
      frame.setVisible(false);
   }

});

frame.setVisible(true);
frame.pack();

Upvotes: 3

user330315
user330315

Reputation:

In your call this.setVisible(false), this probably refers to the button and not the frame.

You need to call setVisible() on the Frame not the Button.

Also make sure you are calling dispose() on the frame to clean up all resources.

Additionally you should also use

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

during creation of the frame, to make sure the windows is properly closed and disposed when the user clicks the "standard" close button in the upper right corner (on Windows).

This tutorial might also help you understand what's going on better:

http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

Upvotes: 2

Related Questions