Java - JComboBox中的复选框 [英] Java - Check Boxes in a JComboBox

查看:475
本文介绍了Java - JComboBox中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个JComboBox,它包含项目而不是文本的复选框。此外,应该可以检查多个项目并从组件中检索所选项目。我应该自定义ComboBoxUI,ComboBoxEditor,ListCellRenderer,ComboPopUp还是其他不同的东西?是否有现有的Java控件来执行此操作?

I would like to make a JComboBox that has check boxes for items instead of text. In addition, it should be possible to check multiple items and retrieve the selected items from the component. Should I be make a custom ComboBoxUI, ComboBoxEditor, ListCellRenderer, ComboPopUp, or something different entirely? Is there an existing Java control that does this?

推荐答案

这很容易实现。发现在这里链接文本

This was fairly easy to implement. Found it here link text

/* * The following code is adapted from Java Forums - JCheckBox in JComboBox URL: http://forum.java.sun.com/thread.jspa?forumID=257&threadID=364705 Date of Access: July 28 2005 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;

public class JComboCheckBox extends JComboBox {
  public JComboCheckBox() { addStuff(); }
  public JComboCheckBox(JCheckBox[] items) { super(items); addStuff(); }
  public JComboCheckBox(Vector items) { super(items); addStuff(); }
  public JComboCheckBox(ComboBoxModel aModel) { super(aModel); addStuff(); }
  private void addStuff() {
    setRenderer(new ComboBoxRenderer());
    addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) { itemSelected(); }
    });
  }
  private void itemSelected() {
    if (getSelectedItem() instanceof JCheckBox) {
      JCheckBox jcb = (JCheckBox)getSelectedItem();
      jcb.setSelected(!jcb.isSelected());
    }
  }
  class ComboBoxRenderer implements ListCellRenderer {
    private JLabel defaultLabel;
    public ComboBoxRenderer() { setOpaque(true); }
    public Component getListCellRendererComponent(JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
      if (value instanceof Component) {
        Component c = (Component)value;
        if (isSelected) {
          c.setBackground(list.getSelectionBackground());
          c.setForeground(list.getSelectionForeground());
        } else {
          c.setBackground(list.getBackground());
          c.setForeground(list.getForeground());
        }
        return c;
      } else {
        if (defaultLabel==null) defaultLabel = new JLabel(value.toString());
        else defaultLabel.setText(value.toString());
        return defaultLabel;
      }
    }
  }
}

这篇关于Java - JComboBox中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆