显示JComboBox的不可选默认值 [英] display a non-selectable default value for JComboBox

查看:439
本文介绍了显示JComboBox的不可选默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JComboBox ,其中包含三个项目 {Personel,Magasinier,Fournisseur}

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

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

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

我在 initComponents();

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

但不起作用。

我该怎么做?

推荐答案

您可以覆盖 JComboBox中的选择代码 model,代码如下面的SSCCE:

You could override the selection code in your JComboBox model, with code such as the following 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.

这篇关于显示JComboBox的不可选默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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