在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中,從而實現多選功能。可以根據實際需求對下拉框和列表的樣式和行為進行定制化。