开发者

Open a window-popup from JMenuItem java

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 com开发者_C百科ponent with inside JButton, JTextField,...

How can i do this ?


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜