2013-08-17 42 views
0

美好的一天每个人,我需要一点点帮助这里。我能够把这些项目连接我的数据库,并显示到的JComboBox,我散乱的时刻是,每一次我改变我的JComboBox该项目的项目时,将显示在我的JTextField是总是在我的JComboBox即使第一项我点击我的JComboBox显示选定项目的JTextField

public void JComboBoxToJTextFlied() 
{ 
    String dataSource = "CheckWriterDB"; 
    String dbURL = "jdbc:odbc:" _ dataSource; 
    String temp = (String)listOfSuppliers.getSelectedItem(); 
    String sql = (select Suppliers from SuppliersTable where Suppliers=?) 

    try 
    { 
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
     Connection connect= DriverManager.getConnection(dbURL, "", ""); 

     PrepareStatement pst = connect.prepareStatement(sql); 
     pst.setString(1, temp); 
     resultSet result = pst.executeQuery(); 

     //My Action perform so that everytime i change the item in my JComboBox 
     the new item will be shown in my JTextField 

     listOfSuppliersCombo.addItemListener(new ItemListener() 
     public void itemStateChange(ItemEvent event) 
     { 
     If(event.getStateChange() == ItemEvent.SELECTED) 
     { 
     try 
     { 
      if(result.next()) 
      { 
       String add = result.getString("Suppliers") 
       newSuppliersEntryField.setText(add); 
      } 

     } 
     catch() 
     { 
      system.out.println("Your error is: " + e) 
     } 
     } 
     } 
    ); 
    } 
    catch(Exception e) 
    { 
    System.out.println("Your error is: " + e) 
    } 


} 

注意到第二项,第三项显示:listOfSupplierCombo是我的JComboBox和newSuppliersEntryField是我的JTextField。

我如何提高我的代码,使每一个我在JComboBox中更改的项目时,它会在我的JTextField显示相同的项目?因为每次我更改项目中的JComboBox将出现在我的JText领域的产品总是在我的组合框的第一个项目,即使我选择了第二,第三,第四等在我的JComboBox。非常感谢。

回答

0

试试:

If(event.getStateChange() == ItemEvent.SELECTED) 
      { 
      event.getSource(); 
// It returns the selected item 
//you also can check it by: 
     System.out.println(event.getSource()); 
}