2013-08-17 79 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()); 
}