2012-04-30 13 views
6

私はJavaコンボボックスとプロジェクトをSQLiteデータベースにリンクしています。私は、関連付けられたIDと名前を持つオブジェクトを持っている場合は、次のユーザーは、従業員の名前を見ているが、ときに私、私は社員コードを盗んことができるようにJava ComboBox異なる名前の値

class Employee { 
    public String name; 
    public int id; 
} 

はJComboBoxのにこれらのエントリを置くの最良の方法は何でしょうあなたのカスタムDefaultComboBoxModelを作成することができ

selEmployee.getSelectedItem(); 

おかげ

答えて

10

最初の方法:toString()をEmployeeクラスに実装し、名前を返すようにします。コンボボックスモデルにEmployeeのインスタンスが含まれるようにします。選択したオブジェクトをコンボから取得すると、Employeeインスタンスが取得され、IDを取得できます。

2番目の方法:toString()が名前以外のもの(デバッグ情報など)を返す場合は、上記と同じ操作を行いますが、カスタムセルレンダラーをコンボに追加設定します。このセルレンダラーは、値をEmployeeにキャストし、ラベルのテキストを従業員の名前に設定する必要があります。

私はあなたがのIDを取得したいときにいつでもResultSetの今

HashMap<Integer, Integer> IDHolder= new HashMap<>(); 

int a=0; 
while(rs.next()) 
{ 
    comboBox.addItem(rs.getString(2)); //Name Column Value 
    IDHolder.put(a, rs.getInt(1)); //ID Column Value 
    a++; 
} 

であなたのJComboBoxを充填する際にこれを行うにはベストとシンプル方法は、このようなHashMapものを使用することだろうと思う

public class EmployeeRenderer extends DefaulListCellRenderer { 
    @Override 
    public Component getListCellRendererComponent(JList<?> list, 
                Object value, 
                int index, 
                boolean isSelected, 
                boolean cellHasFocus) { 
     super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 
     setText(((Employee) value).getName()); 
     return this; 
    } 
} 
0

:ありません。あなたのケースであなたのデータのベクトルを作成するにはVector<Employee> empVec。さらにgetSelectedItem()メソッドをオーバーライドし、getSelectedIndex()メソッドを使用してベクトルから値を取得する必要があります。

6

従業員オブジェクトをJComboBoxに追加し、従業員クラスのtoStringメソッドを上書きしてEmployee名を返します。

Employee emp=new Employee("Name Goes here"); 
comboBox.addItem(emp); 
comboBox.getSelectedItem().getID(); 
... 
public Employee() { 
    private String name; 
    private int id; 
    public Employee(String name){ 
     this.name=name; 
    } 
    public int getID(){ 
     return id; 
    } 
    public String toString(){ 
     return name; 
    } 
} 
+0

レンダラーを使用する方が、 GUIに合わせてString()を呼び出すことができます。 –

3

任意のコンボボックスアイテムのIDを選択することができます。

int Id = IDHolder.get(comboBox.getSelectedIndex()); 
関連する問題