Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

java - Cannot add checkbox to the JList

I'm very new to programming, and I can't add JCheckbox to the JList. There is no error but nothing is displayed.

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an alternative to the JTable solution that trashgod posted, you can also create the appearance of JCheckBoxes in a JList by:

  1. Use a custom renderer for your JList that will show each item as a JCheckBox
  2. Use a custom object in your JList that maintains it's boolean "checked" state
  3. Add a MouseListener to the JList that will set/unset the checked state of each item.

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;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...