Question

I have a JMenu with a JMenuItem, and when I click on this, I need to open a JFrame or window, in other words a component with inside JButton, JTextField,...

How can i do this ?

Was it helpful?

Solution

You can create the JFrame in the same way you created your initial JFrame, and call

setVisible(true);

in the ActionListener of your JMenuItem to make it visible when the menu is clicked.


If you want it to be modal (original frame cannot be accessed unless the new window is closed), you can use a JDialog instead, setting modal to true in the constructor, or calling setModal(true).

OTHER TIPS

I write in answer for good code view:

If i use a JFrame i got this error: "java.lang.IllegalArgumentException: adding a window to a container".

That's my code in actionPerformed method:

PopupFactory factory = PopupFactory.getSharedInstance();
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setBounds(428, 99, 185, 155);

final JButton button = new JButton();
button.setText("Button");
button.setBounds(10, 93, 111, 25);
frame.getContentPane().add(button);

final Popup popup = factory.getPopup(null, frame, 200, 200);
popup.show();

You are confusing "popups" and "windows".

A popup is generally shown when you right click on some object. The popup will display a list of actions that can be performed on that object. For example a text field might have "cut", "copy" and "paste". Read the section from the Swing tutorial on "Bringing Up a Popup Menu" for more information.

A window is used to display other Swing components in a JFrame or JDialog.

Given that you are invoking this Action from a menu item I think you probably want to create and display a modal JDialog, not a JFrame or popup.

Also, while reading the tutorial, read the section on "Using Layout Managers". Using null layouts is not the best way to create a dialog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top