无法向JList添加复选框

时间:2013-07-30 16:00:29

标签: java swing jlist jcheckbox

我是编程新手,我无法将JCheckbox添加到JList。没有错误但没有显示任何内容。

JFrame f=new JFrame();
String[] labels={"a","b","c","d","e"};
JCheckBox[] ch=new JCheckBox[labels.length];

JList list=new JList();

for (int i = 0; i < labels.length; i++) {
    ch[i]=new JCheckBox("CheckBox"+i);
    list.add(ch[i]);
}

JScrollPane pane=new JScrollPane(list);
f.add(pane);
f.setVisible(true);

4 个答案:

答案 0 :(得分:7)

作为trashgod发布的JTable解决方案的替代方案,您还可以通过以下方式在JList中创建JCheckBoxes的外观:

  1. 为JList使用自定义渲染器,将每个项目显示为JCheckBox
  2. 在JList中使用自定义对象,使其保持布尔“已检查”状态
  3. 将一个MouseListener添加到JList,它将设置/取消设置每个项目的已检查状态。

  4. import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class JCheckBoxListDemo implements Runnable
    {
      private JList jlist;
    
      public static void main(String args[])
      {
        SwingUtilities.invokeLater(new JCheckBoxListDemo());
      }
    
      public void run()
      {
        Object[] items = new CheckListItem[] {
            new CheckListItem("Apple"),
            new CheckListItem("Banana"),
            new CheckListItem("Carrot"),
            new CheckListItem("Date"),
            new CheckListItem("Eggplant"),
            new CheckListItem("Fig"),
            new CheckListItem("Guava"),
        };
    
        jlist = new JList(items);
        jlist.setCellRenderer(new CheckBoxListRenderer());
        jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jlist.setVisibleRowCount(5);
        jlist.addMouseListener(new MouseAdapter()
        {
          @Override
          public void mouseClicked(MouseEvent event)
          {
            selectItem(event.getPoint());
          }
        });
    
        KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0);
        Object mapKey = keyStroke.toString();
        jlist.getInputMap().put(keyStroke, mapKey);
        jlist.getActionMap().put(mapKey, new AbstractAction()
        {
          public void actionPerformed(ActionEvent event)
          {
            toggleSelectedItem();
          }
        });
    
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JScrollPane(jlist));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      private void selectItem(Point point)
      {
        int index = jlist.locationToIndex(point);
    
        if (index >= 0)
        {
          CheckListItem item = (CheckListItem)jlist.getModel().getElementAt(index);
          item.setSelected(!item.isSelected());
          jlist.repaint(jlist.getCellBounds(index, index));
        }
      }
    
      private void toggleSelectedItem()
      {
        int index = jlist.getSelectedIndex();
    
        if (index >= 0)
        {
          CheckListItem item = (CheckListItem)jlist.getModel().getElementAt(index);
          item.setSelected(!item.isSelected());
          jlist.repaint(jlist.getCellBounds(index, index));
        }
      }
    
      private class CheckListItem
      {
        private Object item;
        private boolean selected;
    
        public CheckListItem(Object item)
        {
          this.item = item;
        }
    
        @SuppressWarnings("unused")
        public Object getItem()
        {
          return item;
        }
    
        public boolean isSelected()
        {
          return selected;
        }
    
        public void setSelected(boolean isSelected)
        {
          this.selected = isSelected;
        }
    
        @Override
        public String toString()
        {
          return item.toString();
        }
      }
    
      private class CheckBoxListRenderer extends JCheckBox
          implements ListCellRenderer
      {
        public Component getListCellRendererComponent(JList comp, Object value,
                         int index, boolean isSelected, boolean hasFocus)
        {
          setEnabled(comp.isEnabled());
          setSelected(((CheckListItem) value).isSelected());
          setFont(comp.getFont());
          setText(value.toString());
    
          if (isSelected)
          {
            setBackground(comp.getSelectionBackground());
            setForeground(comp.getSelectionForeground());
          }
          else
          {
            setBackground(comp.getBackground());
            setForeground(comp.getForeground());
          }
    
          return this;
        }
      }
    }
    

答案 1 :(得分:3)

JList渲染器可以绘制复选框,但JList不支持单元格编辑器。相反,请考虑单列JTable。对于renderer & editor,类型为Boolean.class的列的默认exampleJCheckBox

答案 2 :(得分:2)

以下是您可能正在寻找的内容:
enter image description here

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CheckBo 
{
    public static void main(String[] args) 
    {
            JFrame f=new JFrame();
            String[]labels={"a","b","c","d","e"};
            JCheckBox[]ch=new JCheckBox[labels.length];

            final DefaultListModel model = new DefaultListModel();

            JList list=new JList(model);
            list.setCellRenderer(new CheckListRenderer());
            for (int i = 0; i < labels.length; i++) {
                //ch[i]=new JCheckBox("CheckBox"+i);
                model.addElement(new CheckListItem("CheckBox"+i));
            }
            JScrollPane pane=new JScrollPane(list);
            list.addMouseListener(new MouseAdapter()
            {
                 public void mouseClicked(MouseEvent event)
                 {
                    JList list = (JList) event.getSource();
                    // Get index of item clicked
                    int index = list.locationToIndex(event.getPoint());
                    CheckListItem item = (CheckListItem)
                       list.getModel().getElementAt(index);
                    // Toggle selected state
                    item.setSelected(! item.isSelected());
                    // Repaint cell
                    list.repaint(list.getCellBounds(index, index));
                 }
            }); 
            f.add(pane);
            f.pack();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
    }
    static class CheckListItem
    {
        private String  label;
        private boolean isSelected = false;

        public CheckListItem(String label)
        {
            this.label = label;
        }
        public boolean isSelected()
        {
            return isSelected;
        } 
        public void setSelected(boolean isSelected)
        {
            this.isSelected = isSelected;
        }
        public String toString()
        {
            return label;
        }
    }

    static class CheckListRenderer extends JCheckBox implements ListCellRenderer
    {
        public Component getListCellRendererComponent(JList list, Object value, int index,boolean isSelected, boolean hasFocus)
        {
            setEnabled(list.isEnabled());
            setSelected(((CheckListItem)value).isSelected());
            setFont(list.getFont());
            setBackground(list.getBackground());
            setForeground(list.getForeground());
            setText(value.toString());
            return this;
        }
    }
}

以上代码的来源为this

答案 3 :(得分:1)

查看此Link,它会为您提供所需内容。

另外,我建议使用JTable而不是JList。 Sun有很多examples here.