JPopupMenu with JCheckBoxMenuItmes

Hi,
I have a JPopupMenu with JCheckBoxMenuItems and JMenuItems.
The default behaviour of the JPopupMenu is, that it closes on selection of a MenuItem. This behaviour is not really nice for the CheckBoxMenuItems !
Does anyone know a workaround?
Thanks,
Elke

I don't have a workaround, sorry. But I think thats not needed too. The behavior you don't seem to like, is consistent with every application I ever used.
When I click on a menuitem, the only actions I expect is that either the menu closes and a command is executed, or another pop-up menu appears where I make my choice.
If you had a menu that doesn't close when you select or deselect a CheckBoxMenuItem, how do you close that menu? I think a MenuItem "Close this menu" would not be appreciated by any user. I use CheckBoxes on menus sparingly, and only for actions that generate an immediate visual response. (For instance Grayscale Image vs. Colored Image).
If you want the user to have more control about options its better you create a small dialog with your choices and an accept/cancel set of buttons.
Sorry I couldn't help with your initial question.

Similar Messages

  • JPopupMenu with a JScrollPane

    I have couple of questions
    1. I want to add a JScrollPane to JPopupMenu, doing this would not make the JPopupMenu visible. Is this doable?
    2. this is not related to question 1
    I have a JPOpupMenu with JMenuItems. When I select one of items and the item selected , I append the String to a JTextArea.
    The focus goes back to th beginning of the textArea, I want the focus to be at the end of string that is appended to the textArea.
    thanx

    I might sounding dense here, but I tried all the suggestions, it does not help. The textArea does not even get displayed.
    Also I noticed another thing, the JtextArea is registered with a mouseListener. But when I right click on JTextField , I get teh popup. Which is strange.
    I have attached the code with the above suggestions.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TextChooserDemo extends JFrame{
         private JTextField field;
         private JLabel label1;
         private JLabel label2;
         private JPanel aPanel ;
         private JPanel bPanel;
         private JTextArea textArea;
        private TextChooser chooser;
        public TextChooserDemo() {
            initComponents();
            chooser=new TextChooser(this,textArea);
        private void initComponents() {
              field = new JTextField(20);
              label1 = new JLabel("Label1");
              textArea = new JTextArea();
              aPanel = new JPanel();
              aPanel = new JPanel();
              aPanel.setLayout(new BorderLayout());
              aPanel.add(label1, BorderLayout.WEST);
              aPanel.add(field, BorderLayout.CENTER);
              label2 = new JLabel("Label2");
              bPanel = new JPanel();
              bPanel.setLayout(new BorderLayout());
              bPanel.add(label2, BorderLayout.WEST);
              aPanel.add(textArea, BorderLayout.CENTER);
            setTitle("Text-Chooser Demo");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            getContentPane().add(aPanel,BorderLayout.NORTH );
            getContentPane().add(bPanel,BorderLayout.CENTER);
            //getContentPane().add(aPanel );
            //getContentPane().add(bPanel);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-500)/2, (screenSize.height-350)/2, 500, 350);
        public static void main(String args[]) {
            new TextChooserDemo().setVisible(true);
    class TextChooser extends JWindow {
        public TextChooser(JFrame parent, JTextArea textArea){
            super(parent);
            this.parent=parent;
            this.textArea=textArea;
            initChooser();
        private void initChooser(){
            textArea.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent evt) {
                    textAreaMouseReleased(evt);
            popupScrollPane = new JScrollPane();
            popupList = new JList();
            popupList.setModel(new AbstractListModel() {
                String[] strings = { "java ", "is ", "cool ", "and ", "nice ", "to ", "have ", "with ", "no ", "error ", ".\n" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    popupList.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent evt) {
    popupListAction(evt);
    popupScrollPane.setViewportView(popupList);
    getContentPane().add(popupScrollPane);
    private void popupListAction(ListSelectionEvent evt) {
    if (evt.getValueIsAdjusting() == false) {
    textArea.append((String)popupList.getSelectedValue());
    try{
    textArea.setCaretPosition(textArea.getLineEndOffset(textArea.getLineCount()-1));
    }catch(BadLocationException ex){ex.printStackTrace();}
    setVisible(false);
    textArea.requestFocus();
    private void textAreaMouseReleased(MouseEvent evt) {
    Point pnt = evt.getPoint();
    int x = (int)pnt.getX()+(int)parent.getX();
    int y = (int)pnt.getY()+(int)parent.getY()+20;
    if( !contains(x,y) ){
    setVisible(false);
    if(evt.isPopupTrigger()){
    setBounds(x,y,200,100);
    setVisible(true);
    private JFrame parent;
    private JTextArea textArea;
    private JScrollPane popupScrollPane;
    private JList popupList;
    thnx again!!!

  • Probleme on JPopupMenu with JDialog

    I use JPopupMenu with JDialog. To display the popup, I use a mousePressed in a panel of the dialog:
    public void mousePressed(MouseEvent e) {
    if( e.getClickCount()==1 && e.getModifiers()==MouseEvent.BUTTON3_MASK && ga!=null ) {
         mpopup.show(e.getComponent(),e.getX(), e.getY());
    It works fine, but when a part of the popup is out of the dialog, the popup doesn't display.
    Is it normal?
    Has someone already had this problem?
    I work with jdk1.3.1_01
    Thanks for your help
    Templ

    When you create your popup menu do this :
    mpopup.setLightWeightPopupEnabled(false);
    I hope this helps,
    Denis

  • JPopupMenu with multiline JMenuItem ?

    Hi there.
    Is it possible to do something like the subject says, a JPopupMenu with multiline JMenuItem's, without using html? I would like to create a JMenuItem with a MultiLineLabel as the argument instead of a String. I'm trying to do this because if i add the MultiLineLabel directly to the JPopupMenu, it displays as i want, but i loose the behaviour inherent to a JMenuItem, the highlighted index, etc.. Any help would be appreciated.

    Here's a workaround:
    JPopupMenu popupMenu = new JPopupMenu();
    // Workaround to stop first menu item being selected
    JMenuItem dummyItem = popupMenu.add(new JMenuItem());
    dummyItem.setPreferredSize(new Dimension(0, 0));
    popupMenu.add("Item 1");
    popupMenu.add("Item 2");
    popupMenu.add("Item 3");
    It works for me!

  • JPopupMenu with a submenu (doesn't work)

    I have a JPopupMenu that displays some info for me and I would like to add a submenu but it doesn't seem to work. I can successfully add the submenu but it doesn't "expand" when I mouse over the submen.
    JPopupMenu pm = new JPopupMenu();
    JMenu submenu = new JMenu("submenu");
    JMenuItem jmi = new JMenuItem(...);
    submenu.add(jmi);
    pm.add(submenu);The popup menu looks as it should and the only thing that is missing is the action that should expand the submenu when I mouse over (and clicking doesn't work either).
    Any ideas?

    I don't think it is my code because I have tried it with other JPopupMenu stuff and it never works. Here is a simple working example of it. If you can modify this code to work I will be a bielver...
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    public class PopUpMenuTest extends JPanel implements MouseListener, MouseMotionListener {
       private JPopupMenu jpm;
       private JFrame frame;
       public PopUpMenuTest() {
          super();
          addMouseListener(this);
          addMouseMotionListener(this);
          JFrame.setDefaultLookAndFeelDecorated(true);
          frame = new JFrame("Testing PopUpMenuTest");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setContentPane(this);
          frame.setSize(600, 400);
          frame.setVisible(true);
       public static void main(String[] args) {
          new PopUpMenuTest();
       public void mouseClicked(MouseEvent me) {
          System.out.println("Mouse clicked...");
          jpm = new JPopupMenu();
          jpm.setLightWeightPopupEnabled(false);
          jpm.add(new JMenuItem("Testing 1"));
          jpm.add(new JMenuItem("Testing 2"));
          jpm.addSeparator();
          JMenu submenu = new JMenu("A submenu");
          JMenuItem menuItem1 = new JMenuItem("An item in the submenu");
          submenu.add(menuItem1);
          JMenuItem menuItem2 = new JMenuItem("Another item");
          submenu.add(menuItem2);
          jpm.add(submenu);
          jpm.setVisible(true);
          jpm.setLocation(frame.getX()+me.getX(), frame.getY()+me.getY());
          jpm.setVisible(true);
       public void mouseMoved(MouseEvent arg0) {
          if (jpm != null) {
             jpm.setVisible(false);
             jpm = null;
       public void mouseEntered(MouseEvent arg0) {}
       public void mouseExited(MouseEvent arg0) {}
       public void mousePressed(MouseEvent arg0) {}
       public void mouseReleased(MouseEvent arg0) {}
       public void mouseDragged(MouseEvent arg0) {}
    }

  • JPopupMenu with submenu

    Hello,
    I have a grid of buttons. If the user clicks a button with the right mouse button,
    a JPopupMenu shows up. The popup menu includes also 2 submenus (JMenu).
    When the user selects a menuitem, I need to know which was the selected button,
    because it identifies the object on which the operation has to be performed.
    If the menuitem is not in a submenu, I can get the button using
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();But if the selected menuitem is in the submenu, popup.getInvoker returns the JMenu (submenu)
    and not the button.
    How do I get which button was pressed?
    thanks Marina

    Sorry it is not clear to me how.
    This is the code that shows the popup
    mb.addMouseListener( new java.awt.event.MouseListener() {
              public void mouseEntered(MouseEvent e) {
              public void mouseExited(MouseEvent e) {
              public void mouseReleased(MouseEvent e) {
              public void mouseClicked(MouseEvent e) {
                   if (e.getButton() == MouseEvent.BUTTON3)
                        JButton button = (JButton)e.getSource();
                        if (button.isEnabled())
                             mcPopup.show(button,0,button.getHeight());
              public void mousePressed(MouseEvent e) {
    The different clicks are then handled by the ActionListener:     if(actionString.equals("ccbinfo")) //default action for left click on the button
                   b = (JButton) arg0.getSource();
              else if (actionString.contains("power")) //action for submenu items
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) ?
              else // action for popup items (not in submenu)
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();
    In the ActionListener the button information from the MouseClicked event is not available,
    how do I pass the button info to the menu?
    The menu is constructed only once, and the attached to the button only when right clicked.     private void buildPopupMenu()
              mcPopup = new JPopupMenu();
              pwrOnPopup = new JMenu("Power on"); //submenu
              pwrOffPopup = new JMenu("Power off"); //submenu
    ... //build and add items
         mcPopup.add(pwrOnPopup);
         mcPopup.add(pwrOffPopup);
    thanks Marina                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu popup = new JPopupMenu();
              menuItem = new JMenuItem("A popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              menuItem = new JMenuItem("Another popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * Create the GUI and show it.  For thread safety,
          * this method should be invoked from the
          * event-dispatching thread.
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • JPopupMenu with JScrollPane

    Hi,
    How can I add a scroll in a JPopupMenu???????
    Thanks,

    Hi,
    How can I add a scroll in a JPopupMenu???????
    Thanks,

  • GlassPane & JPopupMenu with child menus

    I've read the helpful posts on how to get a JPopupMenu to appear over the glasspane and handle mouse events (using setLightWeightPopupEnabled(false)).
    However, my JPopupMenu has child components that are JMenus. The JMenus now have the same problem of not responding to mouse events.
    How do I get JMenu to be heavyweight (or, is there a better way to do this whole thing)?

    FYI. I overcame this by going to a JLayeredPane rather than using the GlassPane.

  • JpopupMenu with a JComboBox problem

    Hi,
    Well I need to make a popupMenu which contains a JComboBox, when I invoke the method show(, ,) of the popupMenu, everything looks fine.
    But when I press on the comboBox to view its data, I can only see the drop list and the popupMenu disappears.
    The problem occurs after that, when I try to choose a selection from the comboBox list, it also disappears without invoking the listener.
    I believe it might be a focusing problem.
    If anyone has a solution, I'd appreciate it??
    Thanks & Regards,
    ES_Coders

    An other solution is to work use a BasicComboPopup
    - import javax.swing.plaf.basic.BasicComboPopup -
    It works quiet well
    You can use a normal JComboBox for storing the entrys.
    See the documentation of the class.
    You should only watch for the add or remove methods. Those methods must be invoked on the JComboBox not on the BasicComboPopup.
    Olek

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • Focus problem when JPopupMenu is shown

    I have compiled and ran the following 'JPopupTest.java' in JDK 1.4.1 on Windows. Kindly conduct the two tests as given below
    First Test :
    ============
    The class shows an editable JComboBox and a JButton when visible. Now click the down-arrow button of the JComboBox and make the drop-down popup visible. Then click on the "OK" button while the popup is visible. The popup gets hidden and a dialog is displayed as it should be.
    Second Test :
    =============
    Run the appilcation again. This time type something in the editable textfield of the JComboBox. A custom JPopupMenu with the text "Hello World" would be visible. Then click on the "OK" button while the popup is visible. The expected dialog is not shown. The custom JPopupMenu gets hidden. Now click on "OK" button again. The dialog is visible now.
    My Desire :
    ===========
    When I click on the "OK" button in the "Second Test" the JPopupMenu should get hidden and the dialog gets displayed (as it happens for the "First Test") in one click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    import java.util.*;
    public class JPopupTest extends JPanel implements DocumentListener, ActionListener
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         JPopupMenu jpopupmenu;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         public JPopupTest()
            vec = new Vector();
               vec.addElement("One");
            vec.addElement("Two");
            vec.addElement("Three");
            vec.addElement("Four");
            vec.addElement("Five");
            vec.addElement("Six");
            vec.addElement("Seven");
            vec.addElement("Eight");
            vec.addElement("Nine");
            vec.addElement("Ten");
            jcombobox = new JComboBox(vec);
            jcombobox.setEditable(true);
            _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
            jtextfield = ((JTextField) _bcbe.getEditorComponent());
            jtextfield.getDocument().addDocumentListener(this);
            add(jcombobox);
            button = new JButton("OK");
            button.addActionListener(this);
            add(button);
            jpopupmenu = new JPopupMenu();
            jpopupmenu.add("Hello World");
         public void insertUpdate(DocumentEvent e)  {changedUpdate(e);}
         public void removeUpdate(DocumentEvent e)  {changedUpdate(e);}
            public void changedUpdate(DocumentEvent e)
            if(!jpopupmenu.isVisible())
            jpopupmenu.show(jcombobox, 0, jcombobox.getHeight());
            jtextfield.requestFocus();
         public void actionPerformed(ActionEvent e)
            JOptionPane.showMessageDialog(this, "OK button was pressed");
         public static void main(String[] args)
            JPopupTest test = new JPopupTest();
            JFrame jframe = new JFrame();
            jframe.getContentPane().add(test);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setSize(200,100);
            jframe.setVisible(true);

    See the code below with auto complete of text. When button is pressed, still TF gets focus after JOptionPane dialog is closed.
    -Pratap
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    public class JPopupTest extends JPanel implements ActionListener {
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         MyComboUI comboUi = new MyComboUI();
         public JPopupTest() {
              vec = new Vector();
              vec.addElement("One");
              vec.addElement("Two");
              vec.addElement("Three");
              vec.addElement("Four");
              vec.addElement("Five");
              vec.addElement("Six");
              vec.addElement("Seven");
              vec.addElement("Eight");
              vec.addElement("Nine");
              vec.addElement("Ten");
              jcombobox = new JComboBox(vec);
              jcombobox.setEditable(true);
              jcombobox.setUI(comboUi);
              add(jcombobox);
              button = new JButton("OK");
              button.addActionListener(this);
              add(button);
              _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
              jtextfield = ((JTextField) _bcbe.getEditorComponent());
              jtextfield.addCaretListener(new CaretListener() {
                        public void caretUpdate(CaretEvent e) {
                             if (!jcombobox.isPopupVisible() && jtextfield.isShowing() &&
                                       jtextfield.hasFocus()) {
                                  jcombobox.showPopup();
                             String text = jtextfield.getText().toLowerCase();
                             int index = -1;
                             for (int i = 0; i < jcombobox.getItemCount(); i++) {
                                  String item = ((String) jcombobox.getItemAt(i)).toLowerCase();
                                  if (item.startsWith(text)) {
                                       index = i;
                                       break;
                             if (index != -1) {
                                  comboUi.getList().setSelectedIndex(index);
                             } else {
                                  comboUi.getList().clearSelection();
                   jtextfield.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent e) {
                             if (e.getKeyCode() == e.VK_ENTER) {
                                  Object value = comboUi.getList().getSelectedValue();
                                  jcombobox.setSelectedItem(value);
                                  jcombobox.hidePopup();
         public void actionPerformed(ActionEvent e) {
              JOptionPane.showMessageDialog(this,"OK button was pressed");
              jtextfield.requestFocus();
         public static void main(String[] args) {
              JPopupTest test = new JPopupTest();
              JFrame jframe = new JFrame();
              jframe.getContentPane().add(test);
              jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jframe.setSize(200,100);
              jframe.setVisible(true);
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList() {
                   return listBox;

  • JPopupMenu doesn't work when invoker is not a Swing JComponent ??

    I've written some code that uses a java.awt.Canvas to draw some stuff, and I want to be able to bring up a popup menu over the canvas.
    The problem is that when I try to show the popup menu with my Canvas as the invoker nothing happens: no popup menu appears.
    I also have problems with other AWT components (e.g. with java.awt.TextArea the popup comes up with two clicks but gets hidden behinf the popup that TextArea decides to provide).
    However everything works fine when I use a Swing widget (e.g. JTextArea or JPanel) as the invoker of my popup menu.
    Is this a bug or an undocumented feature?
    The JPopupMenu.show(...) method will happily accept any AWT Component as the invoker. Also the API documentation says nothing on this issue. Also the Swing tutorials doesn't say anything about this.
    I'm tempted to conclude this is an undocumented feature, but that suprises me. Surely I'm not the first person to try and use JPopupMenu with an AWT widget as invoker? Before I file a bug report, can someone tell me if I'm missing something here?
    I have some code to demonstrate this; all you have to do is comment one line and uncomment another to repoduce this behaviour. Let me know if you would like me to post it.

    Quick followup for anyone reading this topic:
    The suggestion of using JPanel and overriding paintComponent(...) is the way to go. I had thought of doing this to begin with, but felt it would be more effort. It's not. It's the same effort as using AWT canvas, but gives better results, and doesn't stuff up JPopupMenu or anything else that wants to interact with a lightweight component.

  • Scroll bar in JPopupMenu when used in JList

    Hi,
    I want variable list (not combo box) where I can add multiple JMenuItems through JPopupMenu. I have created JList in JScrollPane and I have added multiple JMenuItems one by one but in output I am getting the list of JMenuItems without scrollbar. There is no way I can navigate to last JMenuItem in the JList. Could someone help me with integration of JList, JMenuItems, JPopupMenu with scroll bars?
    Below given is the sample code. GUI components have been added through Netbeans.
    public void updatePopUp()
    final JPopupMenu menu = new JPopupMenu();
    menu.setBorder(null);
    menu.setAutoscrolls(true);
    JMenuItem item = new JMenuItem("JMenuItem");
    item.addActionListener(this);
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    menu.setVisible(true);
    menu.pack();
    varList.add(menu);
    // Set the component to show the popup menu
    /* this.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    public void mouseReleased(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    }

    I was going to say try setting the preferred (or maximum) size of the scrollpane to force it to be no larger than you want.
    But ...
    a) I don't see you putting menu items in a JList in that code. You are putting them directly into the popup menu (aka, the normal way to do things).
    b) Calling setAutoscrolls() on the JPopupMenu does not make it a "scrollable" menu. It is for supporting dragging of components in a scrollpane (usually). Read the API docs.

  • Spawning my own JPopupMenu breaks every single JComboBox in the application

    That's pretty much it.
    I have determined the problem is in no way caused by the contents of the popup menu, but rather the popup menu itself. I have a popup menu which contains only a button which does nothing (I've tried this same thing with just a checkbox, just a radio box, just a text widget...same thing happens). If I bring up the popup and then hide it right away, everything else works fine. If I bring up the popup and click the button, every single combo box in the application (there are dozens) is suddenly in this weird state where even though you can bring up their list popups, selecting items there won't change the contents of the text portion of the widget and in fact an action listener won't even report that an event has taken place.
    When the CBs are in this state, you can use the keyboard to select items. You can also click and HOLD the mouse button and release on your selection and that will properly select the item, but clicking to select list items doesn't work.
    Somehow, the JPopupMenus are swallowing all the mouse pressed events for any other popupmenus in the system. Sounds like a REALLY low level java bug to me...
    OS: Win XP, Win 2000, Win ME, Solaris, FreeBSD, Linux.
    JVMS: Pretty much all the ones you can run on those platforms.
    - Joe

    Of course it's been a while since the original poster brought up this problem, but I was just having this same issue. It had nothing to do with mixing light-weight and heavy-weight components though.
    In my case, I was using a JPopupMenu with some buttons in it as a sort of toolbar flyout, and whenever you would click one of the buttons, all combo boxes in the application would cease to allow simple mouse selection of items in the list. This behavior is evidently related to bug #4492892 and supposedly only applies to the Windows look and feel.
    I think I've found a reasonable work-around. Setting all of the components in the popup menu to be non-focusable (ie. button.setFocusable(false); ) seems to do the trick. Just hoping others might benefit from this solution. Cheers.

Maybe you are looking for