Unhandled Exception
Unhandled Exception

Reputation: 1513

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?

Upvotes: 0

Views: 478

Answers (1)

Ed Brook
Ed Brook

Reputation: 328

You could call menu.setVisible(false); after System.out.println("Button Pressed"); in the Action Listener. e.g:

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);
  }
});

Upvotes: 1

Related Questions