温馨提示×

Java Swing中CheckedListBox的最佳实践

小樊
83
2024-09-03 13:49:08
栏目: 编程语言

在Java Swing中,没有名为CheckedListBox的组件,但是可以使用JList和JCheckBox结合使用来创建一个带有复选框的列表

  1. 首先,创建一个自定义的ListModel,用于存储带有复选框的列表项:
import javax.swing.*;

public class CheckedListModel extends DefaultListModel {
    public void addElement(Object obj) {
        super.addElement(new CheckedListItem(obj));
    }
}
  1. 接下来,创建一个CheckedListItem类,用于存储列表项及其状态(选中或未选中):
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;
    }
}
  1. 创建一个自定义的ListCellRenderer,用于在JList中显示带有复选框的列表项:
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;
    }
}
  1. 在主窗口中添加JList并设置自定义的ListModel和ListCellRenderer:
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);
    }
}

这样,你就创建了一个带有复选框的列表。当用户点击列表项时,相应的复选框将被选中或取消选中。你可以根据需要修改这些代码以适应你的应用程序。

0