0

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?

  • Related question: http://stackoverflow.com/questions/22644909/actionlistener-not-doing-anything/22645236#22645236 – splungebob Mar 26 '14 at 14:12

3 Answers3

1

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

Kevin Workman
  • 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
0

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.

Siger
  • 9
  • 2
0

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);
Dan Temple
  • 2,736
  • 2
  • 22
  • 39