java 为 JComboBox 显示不可选择的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16665688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:35:49  来源:igfitidea点击:

display a non-selectable default value for JComboBox

javaswingjcomboboxpromptlistcellrenderer

提问by Azer Rtyu

I have a JComboBoxthat contains three Items {"Personel", "Magasinier", "Fournisseur"}.

我有一个JComboBox包含三个 Items {"Personel", "Magasinier", "Fournisseur"}

I want this JComboBoxto display the value "Choisir une option :", which is a non-selectable value.

我希望它JComboBox显示 value "Choisir une option :",这是一个不可选择的值。

I tried this code after initComponents();:

我在以下之后尝试了此代码initComponents();

this.jComboBox1.setSelectedItem("Choisir une option :");

but it doesn't work.

但它不起作用。

How can I do that ?

我怎样才能做到这一点 ?

采纳答案by Duncan Jones

You could override the selection code in your JComboBoxmodel, with code such as the following SSCCE:

您可以JComboBox使用以下 SSCCE 代码覆盖模型中的选择代码:

public class JComboExample {

  private static JFrame frame = new JFrame();
  private static final String NOT_SELECTABLE_OPTION = " - Select an Option - ";
  private static final String NORMAL_OPTION = "Normal Option";

  public static void main(String[] args) throws Exception {
    JComboBox<String> comboBox = new JComboBox<String>();

    comboBox.setModel(new DefaultComboBoxModel<String>() {
      private static final long serialVersionUID = 1L;
      boolean selectionAllowed = true;

      @Override
      public void setSelectedItem(Object anObject) {
        if (!NOT_SELECTABLE_OPTION.equals(anObject)) {
          super.setSelectedItem(anObject);
        } else if (selectionAllowed) {
          // Allow this just once
          selectionAllowed = false;
          super.setSelectedItem(anObject);
        }
      }
    });

    comboBox.addItem(NOT_SELECTABLE_OPTION);
    comboBox.addItem(NORMAL_OPTION);

    frame.add(comboBox);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        frame.setVisible(true);
      }
    });
  }
}

This will display a combo box with the intial selection of "- Select an Option -". As soon as the user selects another option, it will not be possible to select the original option again.

这将显示一个组合框,初始选择为“ - Select an Option -”。一旦用户选择了另一个选项,就不可能再次选择原来的选项。

回答by Rawa

I stumbled upon this question and made some Changes to Duncan's answer. My solution looks like this:

我偶然发现了这个问题,并对邓肯的回答做了一些改动。我的解决方案如下所示:

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

public class JEComboBox<T> extends JComboBox<T> {

  public JEComboBox(final T placeHolder){
    setModel(new DefaultComboBoxModel<T>() {
      private static final long serialVersionUID = 1L;
      boolean selectionAllowed = true;

      @Override
      public void setSelectedItem(Object anObject) {
        if (!placeHolder.equals(anObject)) {
          super.setSelectedItem(anObject);
        } else if (selectionAllowed) {
          // Allow this just once
          selectionAllowed = false;
          super.setSelectedItem(anObject);
        }
      }
    });
    addItem(placeHolder);
  }
}

When adding a place holder you create a anonymous object and overriding the toString method. Implementation could look like this:

添加占位符时,您将创建一个匿名对象并覆盖 toString 方法。实现可能如下所示:

public class car{
  String final model;
  public car(String model){
    this.model = model;
  }
}

and the creation of the JEComboBox:

以及 JEComboBox 的创建:

JEComboBox comboBoxWithPlaceHolder = new JEComboBox<Car>(new Car{
  public String toString(){
    return "- Select your car -"
  }
});

Pros

优点

  • Combobox is generic
  • 组合框是通用的

Cons

缺点

  • You need to implement an anonymous subtype of T and Override toString() method and thus wont work on final classes (It can get messy if comboBox hold classes that inherits from a interface, since the anonymous subtype need to implement the interface, thus there will be null returning methods.)
  • 您需要实现 T 和 Override toString() 方法的匿名子类型,因此无法在最终类上工作(如果组合框包含从接口继承的类,则会变得混乱,因为匿名子类型需要实现该接口,因此会有为空返回方法。)

回答by mikeLEI

The easiest and fastest way in my opinion is to use a customized ListCellRenderer

在我看来,最简单快捷的方法是使用定制的 ListCellRenderer

public class TestComboBox<T> extends JComboBox<T> {

  public TestComboBox() {
    super();
    setRenderer(new ItemRenderer());
  }

  public TestComboBox(ComboBoxModel<T> aModel) {
    super(aModel);
    setRenderer(new ItemRenderer());
  }

  public TestComboBox(T[] items) {
    super(items);
    setRenderer(new ItemRenderer());
  }

  public TestComboBox(Vector<T> items) {
    super(items);
    setRenderer(new ItemRenderer());
  }

  class ItemRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus){
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (getSelectedItem() == null && index < 0){
            setText("placeholder");
        }
        return this;
    }
  }
}