Harun ERGUL
Harun ERGUL

Reputation: 5942

Swing how to close JPanel programmatically

My main class extends JPanel and I create a table and a button on this panel.Now I want to close this panel when the user press it.On the internet closing examples are about JFrame.Is there solution for JPanel?

Upvotes: 6

Views: 44251

Answers (5)

Felipe Gallardo
Felipe Gallardo

Reputation: 11

When you extends a JPanel you import the necesary :

 JComponent comp = (JComponent) e.getSource();
  Window win = SwingUtilities.getWindowAncestor(comp);
  win.dispose();

but when you extend for a JFrame you just use this.dispose() or yourFrameInstance.dispose();

Upvotes: 0

Lefteris Bab
Lefteris Bab

Reputation: 787

public void actionPerformed(ActionEvent e) {
  JComponent comp = (JComponent) e.getSource();
  Window win = SwingUtilities.getWindowAncestor(comp);
  win.dispose();
}

e.getSource(): Get Java Component

getWindowAncestor: Returns the first Window ancestor of Component

win.dispose(): Releases all of the native screen resources used by this its subcomponents, and all of its owned children.

Upvotes: 8

Alex
Alex

Reputation: 643

You may try using Frame.pack() again it worked for me.

Upvotes: 3

HellishHeat
HellishHeat

Reputation: 2491

Assuming you want to close your swing application when you press the button. You can just use:

System.exit(0);

Upvotes: 3

forgivenson
forgivenson

Reputation: 4435

If you want to 'close' a JPanel, you can hide it.

myPanel.setVisible(false);

And if/when you want to 'open' it again:

myPanel.setVisible(true);

Upvotes: 7

Related Questions