2015-10-16 71 views
1

我有一个名为Author的数据库表。 AuthorId是类型作者增量和我在Gui(NetBeans)中插入的名称。毕竟我能够在JComboBox中显示所有的名字。如何在每次单击comboBox中的作者时在文本字段中显示其相应的ID? Below is the code that i used in order to display the names coming from the database into the comboBox. how do i do to click in oone of the items and get its respective iD from the database?Java应用程序数据库

+0

我用下面的代码从数据库中获取所有的名字并放在一个组合框中。我现在挣扎的是每次单击组合框时都能够获得相应的AuthorId: conn = Connect.ConnectDB(); pst = conn.prepareStatement(“Select * from Author”); rs = pst.executeQuery(); while(rs.next()) authorId = rs.getInt(“AuthorId”); String authorName = rs.getString(“AuthorName”); authorComboBox.addItem(authorName); } –

+2

请使用此信息编辑您的文章。它是1)不是评论,2)以这种格式不可读。 – CollinD

回答

0

创建Object持有两个idname,并通过这IdItem类的authorComboBox.addItem(new IdItem(1,"Test"));

public class IdItem { 
    private int id; 
    private String description; 

    public IdItem(int id, String description) { 
     this.id = id; 
     this.description = description; 
    } 

    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

    public String toString() { 
     if (description == null) { 
      return ""; 
     } 
     return description; 
    } 

    public boolean equals(Object obj) { 
     if (obj instanceof IdItem) { 
      return ((IdItem) obj).getId() == this.getId(); 
     } 
     return false; 
    } 

    public IdItem clone() { 
     return new IdItem(id, description); 
    } 
} 

注意我有overridetoString()Combox调用这渲染该项目。

当您拨打getSelectedItem()时,combobox将返回选定的IdItem,因此您可以获得该ID。