display a non-selectable default value for JComboBox

前端 未结 3 1045
小蘑菇
小蘑菇 2021-01-13 13:27

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

I want this JComboBox to display

3条回答
  •  粉色の甜心
    2021-01-13 13:57

    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 comboBox = new JComboBox();
    
        comboBox.setModel(new DefaultComboBoxModel() {
          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.

提交回复
热议问题