仅出于显示目的的覆盖toString
方法不是一个好习惯。这也是一个潜在的瓶颈。例如,您需要显示两个不同JComboBox
的人:在其中一个中您只需要显示姓名,而在另一个中您需要显示全名。您只能覆盖Person#toString()
一次方法。
要通过的方法是使用ListCellRenderer。例子:
public class Person {
private String _name;
private String _surname;
public Person(String name, String surname){
_name = name;
_surname = surname;
}
public String getName() {
return _name;
}
public String getSurname() {
return _surname;
}
}
这是图形用户界面:
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Demo {
private void initGUI(){
Person person1 = new Person("First", "Person");
Person person2 = new Person("Second", "Person");
Person[] persons = new Person[]{person1, person2};
/*
* This combo box will show only the person's name
*/
JComboBox comboBox1 = new JComboBox(new DefaultComboBoxModel(persons));
comboBox1.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value instanceof Person){
Person person = (Person) value;
setText(person.getName());
}
return this;
}
} );
/*
* This combo box will show person's full name
*/
JComboBox comboBox2 = new JComboBox(new DefaultComboBoxModel(persons));
comboBox2.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value instanceof Person){
Person person = (Person) value;
StringBuilder sb = new StringBuilder();
sb.append(person.getSurname()).append(", ").append(person.getName());
setText(sb.toString());
}
return this;
}
} );
JPanel content = new JPanel(new GridLayout(2, 2));
content.add(new JLabel("Name:"));
content.add(comboBox1);
content.add(new JLabel("Surname, Name:"));
content.add(comboBox2);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().initGUI();
}
});
}
}
如果您运行此示例,您将看到如下内容:
如您所见,两者都JComboBox
包含Person
对象,但它们的表示在每个中都不同。