嗨我想改变我的组合框的标题,所以当应用程序启动它应该说像选择....现在它只是显示我给它的不同类型的字符串。
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的图片
答案 0 :(得分: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类后,您可以将代码编辑为:
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);