如何在Java Swing中将监听器添加到复选框列表中

时间:2014-04-29 20:32:44

标签: java swing jlist jcheckbox listcellrenderer

我正在尝试为此处的实现中的每个复选框添加一个侦听器:How do I make a list with checkboxes in Java Swing?,但我不确定要实现哪个接口。有没有人有任何建议?

public class CheckBoxList extends JList {
    protected Border noFocusBorder =
            new EmptyBorder(1, 1, 1, 1);

    public CheckBoxList() {
        setCellRenderer(new CellRenderer());
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e){
                int index = locationToIndex(e.getPoint());
                if (index != -1) {
                    JCheckBox checkbox = (JCheckBox)
                            getModel().getElementAt(index);
                    checkbox.setSelected(
                            !checkbox.isSelected());
                    repaint();
                }
            }
        });
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    //adds checkboxes..
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void addCheckbox(JCheckBox checkBox) {
        ListModel currentList = this.getModel();
        JCheckBox[] newList = new JCheckBox[currentList.getSize() + 1];
        for (int i = 0; i < currentList.getSize(); i++) {
            newList[i] = (JCheckBox) currentList.getElementAt(i);
        }
        newList[newList.length - 1] = checkBox;
        setListData(newList);
    }
    @SuppressWarnings("rawtypes")
    protected class CellRenderer implements ListCellRenderer {
        public Component getListCellRendererComponent(
                @SuppressWarnings("rawtypes") JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            JCheckBox checkbox = (JCheckBox) value;
            checkbox.setBackground(isSelected ?
                    getSelectionBackground() : getBackground());
            checkbox.setForeground(isSelected ?
                    getSelectionForeground() : getForeground());
            checkbox.setEnabled(isEnabled());
            checkbox.setFont(getFont());
            checkbox.setFocusPainted(false);
            checkbox.setBorderPainted(true);
            checkbox.setBorder(isSelected ?
                    UIManager.getBorder(
                            "List.focusCellHighlightBorder") : noFocusBorder);
            return checkbox;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

根据@MadProgrammer的评论中显示的hereherehere,您可以使用JTable查看并存储Boolean值在相应的TableModel

image