Mammuth
Mammuth

Reputation: 41

Change title of combobox JAVA

Hi i would like to change the titel of my combobox so when the application starts it should say something like choose.... Right now it just shows the diffrent types of Strings i gave it.

String[] KundLista = { "Normal", "Företag", "Student"};
    JComboBox comboBox = new JComboBox(KundLista);
    comboBox.setToolTipText("Välj vilken typ av Kund du är");       
    comboBox.setBounds(171, 46, 97, 22);
    frame.getContentPane().add(comboBox);
    comboBox.setSelectedIndex(2);

![]Pic of the Frame1

Upvotes: 0

Views: 1272

Answers (1)

Kapparino
Kapparino

Reputation: 988

There are few ways to achieve this. Here is one example:

class MyComboBoxRenderer extends JLabel implements ListCellRenderer {
        private String title;

        public MyComboBoxRenderer(String newTitle) {
            title = newTitle;
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) {
            if (index == -1 && value == null) setText(title );
            else setText(value.toString());
            return this;
        }
}

Once you created MyComboBoxRenderer class, you can edit your code into this:

String[] KundLista = { "Normal", "Företag", "Student"};
JComboBox comboBox = new JComboBox(KundLista);
comboBox.setToolTipText("Välj vilken typ av Kund du är"); 
combobox.setRenderer(new MyComboBoxRenderer("Choose"));  
comboBox.setSelectedIndex(-1); // By default it selects first item, we don't want any selection  
comboBox.setBounds(171, 46, 97, 22);
frame.getContentPane().add(comboBox);

Upvotes: 1

Related Questions