在Java Swing中,沒有名為CheckedListBox的組件,但是可以使用JList和JCheckBox結(jié)合使用來創(chuàng)建一個(gè)帶有復(fù)選框的列表
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);
}
}
這樣,你就創(chuàng)建了一個(gè)帶有復(fù)選框的列表。當(dāng)用戶點(diǎn)擊列表項(xiàng)時(shí),相應(yīng)的復(fù)選框?qū)⒈贿x中或取消選中。你可以根據(jù)需要修改這些代碼以適應(yīng)你的應(yīng)用程序。