Java

Java下拉框的多选功能开发

小樊
111
2024-08-07 03:23:28
栏目: 编程语言

在Java中实现下拉框的多选功能可以使用Swing组件中的JComboBox和JList组合实现。下面是一个简单的示例代码:

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MultiSelectComboBoxExample extends JFrame {

    private JComboBox<String> comboBox;
    private JList<String> list;
    private DefaultComboBoxModel<String> comboBoxModel;
    
    public MultiSelectComboBoxExample() {
        comboBoxModel = new DefaultComboBoxModel<>();
        comboBox = new JComboBox<>(comboBoxModel);
        list = new JList<>();
        
        // 设置下拉框可编辑
        comboBox.setEditable(true);
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedItem = comboBox.getSelectedItem().toString();
                if (!comboBoxModel.getIndexOf(selectedItem).equals(-1)) {
                    comboBoxModel.removeElement(selectedItem);
                } else {
                    comboBoxModel.addElement(selectedItem);
                }
            }
        });

        // 设置列表可多选
        list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    String selectedValue = list.getSelectedValue();
                    if (selectedValue != null) {
                        if (!comboBoxModel.getIndexOf(selectedValue).equals(-1)) {
                            comboBoxModel.removeElement(selectedValue);
                        } else {
                            comboBoxModel.addElement(selectedValue);
                        }
                    }
                }
            }
        });

        // 将列表添加到下拉框的弹出窗口中
        comboBox.setRenderer(new ComboBoxRenderer());
        comboBox.setUI(new MetalComboBoxUI());
        comboBox.addPopupComponent(list);
        
        add(comboBox);
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MultiSelectComboBoxExample();
    }

    class ComboBoxRenderer extends JLabel implements ListCellRenderer<String> {
        @Override
        public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {
            setText(value);
            return this;
        }
    }
}

在上面的示例中,我们使用了JComboBox和JList组合来实现下拉框的多选功能。当用户选择下拉框中的选项时,会将选项添加或移除到ComboBoxModel中,从而实现多选功能。可以根据实际需求对下拉框和列表的样式和行为进行定制化。

0
看了该问题的人还看了