在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);
}
}
這樣,你就創建了一個帶有復選框的列表。當用戶點擊列表項時,相應的復選框將被選中或取消選中。你可以根據需要修改這些代碼以適應你的應用程序。