JTextField 限制字符

JTextField Limit Character

我在连接到 MySQL 数据库的 JFrame 上有一个名为 Reservation ID 的 JTextField。 每当我在数据库中添加新乘客时,在我在其他文本字段中输入乘客姓名和其他详细信息之前,JTextField 应该根据自动增量在 JTextField 中自动为我生成一个新的预订 ID。

我的代码:

    resId = new JTextField();
    try{
        rs = stt.executeQuery("select ReservID as last_id from passenger");
        int lastid = rs.getInt("last_id");
        lastid++;
        resId.setText(String.valueOf(last_id));

    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "cannot retrieve");
    }
    resId.setBounds(432, 178, 126, 22);
    frame.getContentPane().add(resId);
    resId.setColumns(10);

我列 RevervID 的最后一行的值为 003。当我 运行 表单时,它应该在预订 ID 文本字段中显示 004 我如何实现那个?请帮忙.. 谢谢

下图link中的texfield http://i.imgbox.com/wcf9KicU.png

首先使用数据库查询找出最大id-> Select max(id) from mytable

将最大id存储在一个变量中->int max_id= max_id_from_database;

max_id 增加一-> max_id++;

将 max_id 值添加到您的 JTextField-> myJTextField.setText("" + max_id);

已编辑:根据您的代码(只需在 ReservID 之前添加 max 并在 if 条件中添加 rs.next() 并且 ReservID 在您的数据库中必须是整数)。

 resId = new JTextField();
    try{
        rs = stt.executeQuery("select max(ReservID) as last_id from passenger");
        if(rs.next()){
        int lastid = rs.getInt("last_id");
        lastid++;
        resId.setText(String.valueOf(last_id));
        }

    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "cannot retrieve");
    }