在Java Swing中,没有名为CheckedListBox的组件,但是可以使用JList和JCheckBox结合使用来创建一个带有复选框的列表
import javax.swing.*;
public class CheckedListModel extends DefaultListModel {
public void addElement(Object obj) {
super.addElement(new CheckedListItem(obj));
}
}
public class CheckedListItem {
private Object item;
private boolean isChecked;
public CheckedListItem(Object item) {
this.item = item;
this.isChecked = false;
}
public Object getItem() {
return item;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
import javax.swing.*;
import java.awt.*;
public class CheckedListCellRenderer extends JCheckBox implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
CheckedListItem item = (CheckedListItem) value;
setComponentOrientation(list.getComponentOrientation());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setSelected(item.isChecked());
setEnabled(list.isEnabled());
setText(item.getItem().toString());
setFocusPainted(false);
return this;
}
}
import javax.swing.*;
public class CheckedListBoxDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Checked List Box Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
CheckedListModel model = new CheckedListModel();
model.addElement("Item 1");
model.addElement("Item 2");
model.addElement("Item 3");
JList checkedListBox = new JList(model);
checkedListBox.setCellRenderer(new CheckedListCellRenderer());
checkedListBox.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int index = checkedListBox.locationToIndex(e.getPoint());
if (index != -1) {
CheckedListItem item = (CheckedListItem) model.getElementAt(index);
item.setChecked(!item.isChecked());
checkedListBox.repaint();
}
}
});
frame.getContentPane().add(new JScrollPane(checkedListBox));
frame.setVisible(true);
}
}
这样,你就创建了一个带有复选框的列表。当用户点击列表项时,相应的复选框将被选中或取消选中。你可以根据需要修改这些代码以适应你的应用程序。