有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

试图在Java中的一个表单中输入数据,然后再将其转换为另一个表单

我正在尝试允许用户在显示错误消息后用Java填写表单,该消息指示字段为空。目前,对话框弹出,然后表单直接进入下一个表单,不允许用户输入任何内容

以下是我正在使用的代码片段:

 private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {  

       //Confirming that the input fields have values
       String un = UserName.getText().toString();
       if(un.equals("")) {
           JOptionPane.showMessageDialog(null, "Username Required");
       }

       String pw = Password.getText().toString();
       if(pw.equals("")) {
           JOptionPane.showMessageDialog(null, "Password Required");
       }

       //link to HRDBS
       HRDBS dbp = new HRDBS();
       dbp.setVisible(true);
       dbp.pack();
       dbp.setLocationRelativeTo(null);
       this.dispose();

    }                     

谢谢你在这件事上的帮助


共 (1) 个答案

  1. # 1 楼答案

    如果将验证转移到一个单独的方法,并在第一个错误时返回,效果会更好一些。此外,您还可以在一条消息中累积错误

    private boolean validateValues() {
        String un = UserName.getText().toString();
        if(un.equals("")){
    
            JOptionPane.showMessageDialog(null, "Username Required");
            return false;
        }
    
    
        String pw = Password.getText().toString();
        if(pw.equals("")){
    
            JOptionPane.showMessageDialog(null, "Password Required");
            return false;
        }
        return true;
    }
    
    private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
        //Confirming that the input fields have values
        if(validateValues()) {
            //link to HRDBS
            HRDBS dbp = new HRDBS();
            dbp.setVisible(true);
            dbp.pack();
            dbp.setLocationRelativeTo(null);
            this.dispose();
        }
    }