如何在JList(java netbeans)中添加复选框?

时间:2019-02-28 07:14:30

标签: java swing jlist jcheckbox

我已经在JList中成功添加了一个复选框,但是它不能同时选择多个复选框,并且复选框的多选代码不起作用,因此我也添加了图像。

enter image description here

 lstsubsub.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

public class CheckboxListCellRenderer extends JCheckBox implements 
       ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, 
            boolean isSelected, boolean cellHasFocus) {


        setComponentOrientation(list.getComponentOrientation());
        setFont(list.getFont());
        setBackground(list.getBackground());
        setForeground(list.getForeground());
        setSelected(isSelected);
        setEnabled(list.isEnabled());


        setText(value == null ? "" : value.toString());  

        return this;
    }
}

1 个答案:

答案 0 :(得分:1)

不要对JList使用JCheckBoxe,而将JPanelGridLayout一起使用,像这样:

import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
    private final JCheckBox checkReg, checkPerm, checkAcc;

    public Main() {
        super(new GridLayout(0, 1)); //1 column, any number of rows...
        super.add(checkReg = new JCheckBox("User Registration"));
        super.add(checkPerm = new JCheckBox("User Permission"));
        super.add(checkAcc = new JCheckBox("User Accounts"));
    }

    public static void main(final String[] args) {
        final JFrame frame = new JFrame("List of checkboxes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Main());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}