display a non-selectable default value for JComboBox

前端 未结 3 1016
小蘑菇
小蘑菇 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:53

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

    public class TestComboBox extends JComboBox {
    
      public TestComboBox() {
        super();
        setRenderer(new ItemRenderer());
      }
    
      public TestComboBox(ComboBoxModel aModel) {
        super(aModel);
        setRenderer(new ItemRenderer());
      }
    
      public TestComboBox(T[] items) {
        super(items);
        setRenderer(new ItemRenderer());
      }
    
      public TestComboBox(Vector 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;
        }
      }
    }
    

提交回复
热议问题