How do I create a Combobox with multi-selection?

I need to create a multiple choice combo box, how to do this?

+3


source to share


2 answers


There are a few major issues with creating custom combobox popup content (like a multi-select list):
1. The default UI suggests using JList as content to change this behavior, which you will need to change for the entire ComboBoxUI
2. You can't just change the default combobox list of lists to multi-segment due to the fact that at the end only one value gets "selected" and the list has a mouse receiver to select the default poll which will make you unable to select more than one item



So, I recommend that you use a plain JList instead of a combobox, or explore some advanced component libraries like JideSoft - they have this component and more that you can't create quickly with Swing functions.

+2


source


I know the question is pretty old, but for anyone still looking for a solution to this problem, try the following code:



public class ComboSelections {

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, UnsupportedLookAndFeelException {

UIManager.setLookAndFeel((LookAndFeel) Class.forName("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel").newInstance());

final JPopupMenu menu = new JPopupMenu();
JMenuItem one = new JCheckBoxMenuItem("One");
JMenuItem two = new JCheckBoxMenuItem("Two");
JMenuItem three = new JCheckBoxMenuItem("Three");
JMenuItem four = new JCheckBoxMenuItem("Four");
menu.add(one);
menu.add(two);
menu.add(three);
menu.add(four);


final JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (!menu.isVisible()) {
            Point p = button.getLocationOnScreen();
            menu.setInvoker(button);
            menu.setLocation((int) p.getX(),
                    (int) p.getY() + button.getHeight());
            menu.setVisible(true);
        } else {
            menu.setVisible(false);
        }

    }
});

one.addActionListener(new OpenAction(menu, button));
two.addActionListener(new OpenAction(menu, button));
three.addActionListener(new OpenAction(menu, button));
four.addActionListener(new OpenAction(menu, button));

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(button);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

private static class OpenAction implements ActionListener {

    private JPopupMenu menu;
    private JButton button;

    private OpenAction(JPopupMenu menu, JButton button) {
        this.menu = menu;
        this.button = button;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        menu.show(button, 0, button.getHeight());
    }
}
}

      

+6


source







All Articles