1

Do you know how can I close JFrame window while I am opening another? I know how it works on buttons but now I want do the same for menu items.

Here is my code :

    public static void main(String[] args) {
    JFrame frame = new JFrame("Test");
    frame.setVisible(true);
    frame.setSize(200, 200);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JLabel label = new JLabel("Hello");
    JPanel panel = new JPanel();
    frame.add(panel);
    panel.add(label);

    JMenuBar menu = new JMenuBar();
    frame.setJMenuBar(menu);
    JMenu action = new JMenu("Action");
    menu.add(action);
    JMenuItem Info = new JMenuItem("Info");
    action.add(Info);

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • *"close JFrame window while I am opening another?"* 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) 2) For many components in one space, use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as seen in this [short example](http://stackoverflow.com/a/5786005/418556). 3) Alternately, perhaps convert one of the frames to a modal `JDialog`. – Andrew Thompson Dec 13 '13 at 17:16
  • BTW - For better help sooner, post an [SSCCE](http://sscce.org/) that works with buttons, and adds a `Next GUI` menu item. Remove the unnecessary cruft, like the other menu items etc. – Andrew Thompson Dec 13 '13 at 17:49

1 Answers1

3

I know how it works on buttons but now I want do the same for menu items.

It works the same way for menu items. You add an ActionListener to the menu item. You should be able to use the same ActionListener that you use for the button.

The question is why are you closing/opening frames? Generally you would either:

  1. display a child dialog to display/prompt for more information
  2. Use a Card Layout to swap panels in the main frame.
camickr
  • 321,443
  • 19
  • 166
  • 288
  • I think I will use Card Layout. I dont know why but some errors appeard when I was trying to do this that way: make new class and add this to menuitem.addActionListener and later in this class call frame.dispose(). But this move is not available from the class(did not see the frame?) so I decided to write here. – user3100234 Dec 13 '13 at 18:03