在Java Swing中创建带有复选框的列表,可以使用DefaultListModel
和JList
组件。以下是一个简单的示例:
import javax.swing.*;
import java.awt.*;
public class CheckboxList {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Checkbox List");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 200));
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("Item 1");
listModel.addElement("Item 2");
listModel.addElement("Item 3");
JList<String> list = new JList<>(listModel);
list.setCellRenderer(new CheckboxListCellRenderer());
list.addMouseListener(new CheckboxListMouseAdapter(list));
JScrollPane scrollPane = new JScrollPane(list);
frame.add(scrollPane);
frame.setVisible(true);
}
}
class CheckboxListCellRenderer extends JCheckBox implements ListCellRenderer<String> {
public CheckboxListCellRenderer() {
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
}
@Override
public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {
setComponentOrientation(list.getComponentOrientation());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setSelected(isSelected);
setEnabled(list.isEnabled());
setText(value);
return this;
}
}
class CheckboxListMouseAdapter extends MouseAdapter {
private final JList<String> list;
public CheckboxListMouseAdapter(JList<String> list) {
this.list = list;
}
@Override
public void mouseClicked(MouseEvent e) {
int index = list.locationToIndex(e.getPoint());
if (index != -1) {
boolean isSelected = list.isSelectedIndex(index);
list.setSelectionInterval(index, index);
list.removeSelectionInterval(index, index);
list.ensureIndexIsVisible(index);
}
}
}
在这个示例中,我们创建了一个带有复选框的列表,并添加了一些示例项目。当用户点击列表项时,复选框将被选中或取消选中。这个示例使用了CheckboxListCellRenderer
和CheckboxListMouseAdapter
来实现复选框的功能。
领取专属 10元无门槛券
手把手带您无忧上云