覆蓋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;
}
}
這裏是GUI:
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();
}
});
}
}
如果運行這個例子,你會看到這樣的內容:
![enter image description here](https://i.stack.imgur.com/SV5dH.jpg)
正如你可以看到這兩個JComboBox
包含Person
對象,但它們的表示形式在每個對象中都不相同。
什麼是目標,因爲那裏(沒有問,描述,不是在這裏發佈的代碼只是猜測)是兩個三個差異和最簡單的方法,沒有人知道沒有SSCCE(更好和說成千上萬的工作)或關於 – mKorbel
默認情況下,Swing默認返回toString或Object(用Java實現的所有可能的數據類型) – mKorbel