【问题标题】:jtextfiled not retrieving the value picked from comboboxjtextfield 没有检索从组合框中选择的值
【发布时间】:2019-05-31 06:59:16
【问题描述】:

我想检索从组合框中选择的值到 jtextfield。根据我的 UI 组合框位于第 4 位。所以我编码:

pst.setString(4, (String)cmbPaySub.getSelectedItem());

和错误弹出:

参数索引超出范围。(4>参数个数,即1"。

我尝试过编码;

pst.setString(1, (String)cmbPaySub.getSelectedItem());

既不会弹出错误,也不会出现值。

private void cmbPaySubActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sipnena", "root", "");
        String sql="select * from payments where cmbSubject=?";
        PreparedStatement pst=con.prepareStatement(sql);
        pst.setString(4, (String)cmbPaySub.getSelectedItem());

        ResultSet rs=pst.executeQuery();

        while(rs.next()){
            txtFee.setText(rs.getString("Fee"));
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}      

请帮助我检索 jtextfield 的值。

【问题讨论】:

  • pst.setString(4 它的pst.setString(1 索引位置将从1 开始。
  • 嗨,我也编码为 1。但什么也没发生
  • 意味着出现同样的错误?
  • 您想从 cmbPaySub 接收数据到 txtFee?如果它是正确的,那不是你的代码的意思
  • SatyaTNV 不是错误。也没有获得价值。

标签: java mysql netbeans


【解决方案1】:

在读取结果时,您会在循环中将整个文本替换为结果的值,因此只会显示最后一个值:

while(rs.next()){
    txtFee.setText(rs.getString("Fee"));
}

你应该连接所有的值,然后设置文本:

StringBuilder text = new StringBuilder();
while(rs.next()){
    text.append(rs.getString("Fee"));
    text.append("\n");
}
txtFee.setText(text.toString());

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多