I am new to swing and I am wondering how to create functionality that when a button is clicked a new Jframe opens? e.g if you click on "Search" then a new screen pops up allowing the user to search by a specific criteria?
3 Answers
You could just create the second JFrame the same way you create the first one.
But what you're looking for is probably a dialog: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
If your question is about how to do something when a button is clicked, you're looking for an ActionListener: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

- 41,537
- 9
- 68
- 107
-
Yes but i am wondering how you link the button to the new jframe, i.e. when its clicked then the new frame opens – Mar 26 '14 at 13:53
First you need to implement an ActionListener on your button to define what is happening when it is clicked. Inside this Actionlistener, just call a method that creates a new JFrame with the appropriate content.
You can also create several JPanel and switch between them instead of opening new frames.

- 9
- 2
Here's an example from an application I'm working on at the minute. I pass the text through so that it can be displayed on the new screen, but there's no need to do that if you don't need to.
I have a method within a class called PopupScreen
that creates a new Frame
private static void createWindowWithText(final String text) {
final JFrame popup = new JFrame();
popup.setPreferredSize(new Dimension(600,450));
//Add in whatever components you want
popup.pack();
popup.setLocationRelativeTo(null);
popup.setVisible(true);
}
This is then called from an action:
private final AbstractAction showTextAction = new AbstractAction("Show Text") {
public void actionPerformed(final ActionEvent e) {
PopupScreen.createWindowWithText("Some Text");
}
};
And this action is linked to button as follows:
this.showTextButton.setAction(showTextAction);

- 2,736
- 2
- 22
- 39