2014-01-10 26 views
0

我在名为customer的数据库中有一个表,它具有类似代码和名称的属性。我在其他表格中调用了客户的价值并使用组合框显示。我在组合框中显示了代码,我想要做的是当我在组合框中选择代码时,值'name'可以显示在文本字段中,'name'代表基于代码显示。如何根据Java中的combobox选项设置文本字段值?

这里是我的代码:

try { 
     Connections con = new Connections(); 
     con.setConnections(); 
     String sql = "select * from customer"; 
     Statement stat = con.conn.createStatement(); 
     ResultSet rs=stat.executeQuery(sql);   
     while (rs.next()){ 
     cmb_custCode.addItem(rs.getString("custCode")); 

     txt_custName.setText(rs.getString("custName")); // i'm confused in here, how can i call the name based on the code 
     } 
} 

catch(Exception e){ 
    e.printStackTrace(); 
    } 
} 

例如:

当在组合框中选择了码“B0001”,JTextField的还必须显示“鲍勃”,因为代码B0001是属于鲍勃。

+0

你能发表一些代码吗? – DLJ

+0

如何命名存储/检索?它是否与您在组合框中放置的值相关联?问题是语言和抽象是可以回答的 – MadProgrammer

+0

你可以使用javascript来做到这一点.. –

回答

2

编辑:

好的。假设你有一个用户Bob和他的codeB001

ItemStateChanged方法

... 
String code = (String) cmb.getSelectedItem(); 
try{ 

String sql = "SELECT * FROM customer WHERE code='"+code"'" 
PreparedStatement prst = con.prepareStatement(); 
ResultSet rs = prst.executeQuery(sql); 
String name = ""; 

while(rs.next()){ 

name = rs.getString('name'); 
} 
txt.setText(name); 
}catch(Exception ex){ 
} 

你不应该实际连接的itemStateChanged里面,但是这仅仅是一个例子。

+0

ehm,但这不是我的目标,例如: 当代码'B0001'在组合框中被选中时,Jtextfield也必须显示“Bob”,因为代码B0001属于Bob – Ayharu

+0

看看编辑答案 – DLJ

+0

我试过了,但仍然没有得到价值 – Ayharu

0

在您自己的示例代码中,您可以将封闭类声明为ActionListener。然后使用实施一个ActionListener时,声明你cmb_custCode

... 
cmb_custCode.addActionListender(this); 
... 

后下面,你必须实现该方法的actionPerformed()。我从那儿剽窃如下:http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners但适于从步道上的示例代码

public void actionPerformed(ActionEvent e) { 
    JComboBox cb = (JComboBox)e.getSource(); 
    String custCode = (String)cb.getSelectedItem(); 
    updateLabel(custCode); 
} 

我保持updateLabel(字符串custCode)的封装。您可以假设该方法被定义为类似于:

private void updateLabel(String code) { 
    txt_custName.setText(map_cust.get(code)); 
} 

我已经用map_cust将一个Map映射到它中。这只是代码和名称之间的映射,存储在现场

Map<String, String> map_cust = new HashMap<String, String>(); 

并填充它,这会去你的代码,只需检索结果集

... 
cmb_custCode.addItem(rs.getString("custCode")); 
map_cust.put(rs.getString("custCode"), rs.getString("custName"); 

所以以后,当你得到你的结果设置,你填充一张地图和你的组合框,当客户端从组合框中选择项目时,他会触发并执行actionPerformed,进入已注册的监听器,在该监听器中操作事件以获取所选项目,其中的字符串是关键字到map_cust,包含映射键,值对,custCode映射到custName。当该名称从地图中拉出时,可用于更新标签的文本。

0

这是我的代码,它解决了我的问题。希望它对你也有用:)。

private void fillText(){ 
String code = (String) cmb_custCode.getSelectedItem(); 
try { 

     Connections con = new Connections(); 
     con.setConnections(); 
     String sql = "select * from customer WHERE custCode='"+code +"'"; 
     Statement stat = con.conn.createStatement(); 
     ResultSet rs=stat.executeQuery(sql); 


      while (rs.next()){ 
      txt_custName.setText(rs.getString("custName")); 
     } 



} 


catch(Exception e){ 
    e.printStackTrace(); 

} 
相关问题