How to create a drop-down list in java swing with

2019-01-19 05:07发布

I'm aware of JList and JComboBox. I need the combo box drop down functionality with multiple selection functionality that JList provides.

This is because the contents of the list are too huge to be displayed using a simple list. I also need to select multiple items, otherwise I would have been content with JComboBox.

Any suggestions?

4条回答
迷人小祖宗
2楼-- · 2019-01-19 05:25

When using multi-select, it's better to use a list than a combo box. As GUI metaphors go, people expect a combo box to be single select, whereas lists can be either.

the contents of the list are too huge to be displayed using a simple list

Place the JList in a JScrollPane. You can call setVisibleRowCount(int) on the JList to specify how many rows at a time should be shown.

查看更多
▲ chillily
3楼-- · 2019-01-19 05:27

You can make a custom cell renderer for the combobox and add checkboxes to that components, so you can check and uncheck them. You have to make something like this:

public class MyComboBoxRenderer implements ListCellRenderer {

    private String[] items;
    private boolean[] selected;

    public MyComboBoxRenderer(String[] items){
         this.items = items;
         this.selected = new boolean[items.lenght];
    }

    public Component getListCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int index) {
         // Create here a JLabel with the text
         // Create here a JCheckBox
         // Add them to a layoutmanager
         return this;
    }

    public void setSelected(int i, boolean flag)
    {
         this.selected[i] = flag;
    }

}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-19 05:27

If your data has a hierarchical character, consider NetBeans' Outline component, discussed in Announcing the new Swing Tree Table and in this answer. Here's the Current Development Version of the API.

查看更多
爷、活的狠高调
5楼-- · 2019-01-19 05:29

To achieve the described functionality, I finally decided to "abuse" the JMenuBar and add to it several JCheckBoxMenuItems. The GUI then perfectly fits the purpose (at least for me), it is just the handling of the ItemEvent that risks to become a bit annoying.

(finally there, I defined some bit logic over the items, and then may restrict myself to handling only one type of event)

查看更多
登录 后发表回答