4

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

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

I tried this code after initComponents(); :

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

but it doesn't work.

How can I do that ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Azer Rtyu
  • 329
  • 4
  • 9
  • 18

3 Answers3

5

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.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • 2
    A similar approach is examined [here](http://stackoverflow.com/a/5231915/230513). – trashgod May 21 '13 at 09:56
  • 1
    +1 but to see [Combo Box Prompt](http://tips4java.wordpress.com/2008/10/18/combo-box-prompt/) by @camickr, reason why I don't post here any code or wrote an answer, any my answers will be about how reinvent the wheel, edited tags for better answers – mKorbel May 21 '13 at 10:21
2

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:

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

and the creation of the 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.)
Rawa
  • 13,357
  • 6
  • 39
  • 55
1

The easiest and fastest way in my opinion is to use a customized 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;
    }
  }
}
mikeLEI
  • 11
  • 4