2

私はこのJava ComboBox Different Value to Nameのようなかなり似た問題を抱えています

私はすでにコードを変更しているので、Employee-Object を取得します (上記のリンクのクラス名は であるため、クラス名を変更しましたEmployee)。

私の場合、toString()上書きしたくないメソッドが既にあります。(別の場所で必要です)

しかし、私はこのtoString()メソッドをJCombobox. しかし、それは自動的に行います。

文字列を返したくない! オブジェクトが必要です。

JCombobox の作成中に「別のtoString()方法を使用してみましょう」と言う方法はありますか?toStringDifferent()

this.comboEmployees = new JComboBox(new EmployeeComboboxModel(getEmployees())); 
// this will give me the toString-method's return-value of the Employee object. 
// But i want the toStringDifferent() method's result.

ありがとう!

4

3 に答える 3

6

実際、を使用しないtoStringことは良い習慣であるとさえ考えられています。

comboEmployees.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList list,
                                               Object value,
                                               int index,
                                               boolean isSelected,
                                               boolean cellHasFocus) {
        Employee employee = (Employee)value;
        value = employee.toStringDifferent();
        return super.getListCellRendererComponent(list, value,
                index, isSelected, csellHasFocus);
    }
});
于 2012-11-19T19:29:00.937 に答える
1

を使用しListCellRendererます。例は、Swingチュートリアルにあります。

別の方法は、独自のtoString()メソッドを定義するオブジェクト内にオブジェクトをラップすることです。

于 2012-11-19T19:30:17.097 に答える
0

JComboBoxを作成し、toStringメソッドを実装する必要があります。

例:

public class        MyComboBox
    extends     JComboBox
{
  public String toString() {
    return "My toString";
    }
}
于 2012-11-19T19:29:25.090 に答える