How to lose focus with JMenuItem or close JPopupMenu
Clash Royale CLAN TAG#URR8PPP
How to lose focus with JMenuItem or close JPopupMenu
The following example generates a popup menu.
The popup menu contains 2 items.
One is a JLabel and the other is a JTextField.
When either item is clicked, a simple statement is printed.
When the JLabel menu item is clicked, the popup menu goes away.
When the JButton menu item is clicked, the popup menu remains.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
public class JPopupExample1
public static void main(String argv) throws Exception
final JPopupMenu menu = new JPopupMenu();
JFrame frame = new JFrame("PopupSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuItem item = new JMenuItem("Item Label");
item.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("Label Pressed"); );
menu.add(item);
JToggleButton jTbutton = new JToggleButton("Click Me");
jTbutton.setToolTipText("Test Buttons");
jTbutton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("Button Pressed"); );
menu.add(jTbutton);
frame.setLayout(null);
JLabel label = new JLabel("Right Click here for popup menu");
label.setLocation(10, 10);
label.setSize(250, 50);
frame.add(label);
label.setComponentPopupMenu(menu);
frame.setSize(350, 250);
frame.setVisible(true);
Is there a simple way to lose focus (without sending it to another Component) after clicking the JButton so the Popup menu goes away?
1 Answer
1
You could call menu.setVisible(false);
after System.out.println("Button Pressed");
in the Action Listener. e.g:
menu.setVisible(false);
System.out.println("Button Pressed");
JToggleButton jTbutton = new JToggleButton("Click Me");
jTbutton.setToolTipText("Test Buttons");
jTbutton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("Button Pressed");
menu.setVisible(false);
);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That worked. Thanks.
– Unhandled Exception
Aug 10 at 17:42