0

Would it be possible to create a custom JMenuItem that contains list of checkbox? Example is the excel filter popup menu:

So far, what I've done is like this:

JPopupMenu headerPopup = new JPopupMenu();
JMenuItem clearfilter = new JMenuItem ("Clear Filter From Time");
JMenu filter = new JMenu("Number Filter");
filter.add(new JMenuItem("Equals.."));
filter.add(new JMenuItem("Not Equal.."));


JPanel checkBoxItems = new JPanel();

JCheckBox[] checkBoxes = new JCheckBox[200];
initList(checkBoxes);
JList list = new CheckBoxList();
list.setModel(new ListModel(checkBoxes));
JScrollPane scrollPane = new JScrollPane(list);

checkBoxItems.setLayout(new BorderLayout());
checkBoxItems.add(scrollPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 3));
buttonPanel.add(new JPanel());
buttonPanel.add(new JButton("Ok"));
buttonPanel.add(new JButton("Cancel"));
checkBoxItems.add(buttonPanel, BorderLayout.SOUTH);

headerPopup.add(clearfilter);
headerPopup.add(filter);
headerPopup.add(checkBoxItems);

The content of checkBoxItems panel is a JList of JCheckBox and two buttons. The problem is when the cursor goes inside the panel, Number Filter Menu Item will still get selected and its PopupMenu will still be shown even though the cursor already goes to the panel.

I tried this but didn't work, any other way?:

    checkBoxItems.addMouseListener(new MouseAdapter() 
    {
        @Override
        public void mouseEntered(MouseEvent e) 
        {
            filter.setArmed(false);
            filter.setSelected(false);
        }
    });
imarefe
  • 5
  • 4

1 Answers1

2
  • use JCheckBoxMenuItem, put them to the ButtonGroup

  • checkBoxItems.addMouseListener(new MouseAdapter() should be ChangeListener, together with getButtonModel

  • those events are implemented in API directly, not required to add MouseListener,

  • ButtonModel is required only for part of mouse and key events that aren't implemented or not implemented confortly in the API

mKorbel
  • 109,525
  • 20
  • 134
  • 319