如何在Java中显示组合框中的数据

时间:2018-06-07 14:21:33

标签: java swing combobox

我正在尝试根据我的jcombobox中的选择在文本字段中显示数据。我使用getSelectedItem但是出了点问题,我无法理解。有时只会出现最后一个idusers,如果我从组合框中选择另一个,它什么都不做。我的代码如下所示:

    try {
            Connection cone = getConnection();
            System.out.println("Connection established successfully");

            String sql = "SELECT * FROM users\n"
                    + "left JOIN teacher ON users.idusers = teacher.idteacher\n"
                    + "WHERE teacher.idteacher IS NULL;";

            pst = cone.prepareStatement(sql);
            rs = pst.executeQuery();

            while (rs.next()) {

                suser.addItem((rs.getString("firstname") + " " + rs.getString("lastname") + " " + rs.getString("idusers")));
            }

            String tmp = String.valueOf(suser.getSelectedItem());
            String sql1 = "SELECT * FROM `users` WHERE lastname = ?";
            try {
                pst = cone.prepareStatement(sql1);
                pst.setString(0, tmp);
                rs = pst.executeQuery();
                if (rs.next()) {
                    String add1 = rs.getString("idusers");
                    sserial.setText(add1);
                    String add2 = rs.getString("lastname");
                    sserial.setText(add2);
                }

            } catch (Exception ex) {
            }

        } catch (SQLException ex) {
            System.out.println("ERROR: Connection not established");
            ex.printStackTrace(System.out);
        }

1 个答案:

答案 0 :(得分:0)

将此 ActionListener 添加到您的jComboBox。 一旦触发任何操作 ....它将从jComboBox 获取所选项目,并将其设置为jTextField的文本

jComboBox.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
  jTextField.setText(String.valueOf(jComboBox.getSelectedItem));
}
});

如果ActionListener 没有解决您的问题,您只需使用ItemListener ,如下所示: -

jComboBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
 jTextField.setText(String.valueOf(jComboBox.getSelectedItem));  
}
});