将JComboBox中的选定项显示为JTextField

时间:2023-01-19 10:36:16

Good day every one, i need a little bit of help here. I was able to connect my database and show those item to a JComboBox, my straggle as of the moment is that every time i change the item on my JComboBox the item that will show on my JTextField is always the first item in my JComboBox even if i click the second or third item show in my JComboBox

每个人都过得愉快,我需要一点帮助。我能够连接我的数据库并将这些项目显示给JComboBox,我现在的摇摆是每当我更改JComboBox上的项目时,我的JTextField上显示的项目始终是我的JComboBox中的第一项,即使我点击我的JComboBox中的第二或第三项显示

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)
   }


}  

note: listOfSupplierCombo is my JComboBox and newSuppliersEntryField is my JTextField.

注意:listOfSupplierCombo是我的JComboBox,newSuppliersEntryField是我的JTextField。

How do i improve my codes so that every time i change the item in my JcomboBox it will show the same item in my JTextField? Because everytime i change the ITem in JcomboBox the item that will appear in my JText field is always the first item in my comboBox even if i chose the second, third, fourth and so on in my Jcombobox. Thank you so much.

我如何改进我的代码,以便每次我更改JcomboBox中的项目时,它将在我的JTextField中显示相同的项目?因为每次我更改JcomboBox中的ITem时,即使我在我的Jcombobox中选择了第二个,第三个,第四个等,我的JText字段中出现的项目也始终是我的comboBox中的第一个项目。非常感谢。

1 个解决方案

#1


0  

Try it:

尝试一下:

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

#1


0  

Try it:

尝试一下:

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