更改组合框的标题 JAVA

Change title of combobox JAVA

您好,我想更改我的组合框的标题,因此当应用程序启动时,它应该显示诸如选择...之类的内容。现在它只显示我给它的不同类型的字符串。

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);

![]相框图片1

实现这一点的方法很少。这是一个例子:

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;
        }
}

创建 MyComboBoxRenderer class 后,您可以将代码编辑为:

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);