java:验证 GUI 中的所有文本字段是否已完成

发布于 2024-11-16 00:46:41 字数 5747 浏览 2 评论 0原文

我正在尝试创建一个允许某人设置帐户的 GUI。我想验证按下创建帐户按钮时所有文本字段是否完整。最好的方法是什么?我正在附加我的代码,但我对文本字段是否完整的验证不起作用。

请参阅下面的代码:

public class GUIaccounts extends JFrame{

private JLabel name;
private JLabel initDeposit;
private JLabel chooseAccount;
private JLabel empty;
private JTextField nameTextField;
private JTextField initDepositTextField;
private JPanel dataPanel;
private JPanel accountTypePanel;
private JRadioButton savingsAccount;
private JRadioButton premiereChecking;
private ButtonGroup radioButtonGroup;
private JButton createAccountButton;
private JPanel createAccountPanel;
private Bank myBank;



public GUIaccounts(){
    setTitle("Create an Account");
    setSize(1000,1000);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    buildPanels();
    setVisible(true);
    pack();
    setLocationRelativeTo(null);
     myBank=new Bank();

}

private void buildPanels(){
    //create the panels
    dataPanel= new JPanel();
    dataPanel.setLayout(new GridLayout(2,2));
    accountTypePanel=new JPanel();
    accountTypePanel.setLayout(new GridLayout(3,1));
    createAccountPanel=new JPanel();
    createAccountPanel.setLayout(new FlowLayout());
    //create labels
    name=new JLabel("Enter Name:");
    Border border = LineBorder.createBlackLineBorder();
    name.setBorder(border);
    initDeposit=new JLabel("Enter Initial Deposit:");
    initDeposit.setBorder(border);
    chooseAccount=new JLabel("Choose Account:");
    empty=new JLabel(" ");
    //create text fields
    nameTextField=new JTextField();
    initDepositTextField=new JTextField();
    //create buttons
    savingsAccount = new JRadioButton("Savings Account");
    premiereChecking =new JRadioButton ("Premiere Checking Account");
    createAccountButton=new JButton("Create Account");
    //add labels and field to the panel
    dataPanel.add(name);
    dataPanel.add(nameTextField);
    dataPanel.add(initDeposit);
    dataPanel.add(initDepositTextField);
    //add button to the panel
    accountTypePanel.add(chooseAccount);
    accountTypePanel.add(empty);
    accountTypePanel.add(savingsAccount);
    accountTypePanel.add(premiereChecking);
    createAccountPanel.add(createAccountButton);

    //add actionListeners to the buttons
    savingsAccount.addActionListener(new RadioButtonListener());
    premiereChecking.addActionListener(new RadioButtonListener());
    createAccountButton.addActionListener(new createAccountListener());
    //add focus to the text field
    nameTextField.addFocusListener(new nameFieldListener());
    initDepositTextField.addFocusListener(new initDepositFieldListener());
    //add panels to the contentPane
    add(dataPanel, BorderLayout.NORTH);
    add(accountTypePanel, BorderLayout.CENTER);
    add(createAccountPanel, BorderLayout.SOUTH);
    //group radio buttons
    radioButtonGroup= new ButtonGroup();
    radioButtonGroup.add(savingsAccount);
    radioButtonGroup.add(premiereChecking);
}
    private class createAccountListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            String name=null;
            Double amount=null;
            if (savingsAccount.isSelected()){
                name=nameTextField.getText();
                amount=Double.valueOf(initDepositTextField.getText());
                if(name!=null && amount !=null){
                try{

                    SavingsAccount account=new SavingsAccount(name,AccountIDs.getNextID(), amount);
                    myBank.addAccount(account);
                    JOptionPane.showMessageDialog(null,"Account setup was successful" + myBank.toString());
                }



                catch(Exception e1){
                    JOptionPane.showMessageDialog(null,"Unable to set up account. " +e1.getMessage());
                }
            }
                else{
                    JOptionPane.showMessageDialog(null, "All fields must be completed in order to set up account");
                }
            }

            else if(premiereChecking.isSelected()){
                name=nameTextField.getText();
                amount=Double.valueOf(initDepositTextField.getText());
                if(name!=null && amount!=null){
                try{
                    PremiereCheckingAccount account=new PremiereCheckingAccount(name, AccountIDs.getNextID(),amount);
                    myBank.addAccount(account);
                    JOptionPane.showMessageDialog(null,"Account setup was successful" +myBank.toString());
                }
                catch(Exception e1){
                    JOptionPane.showMessageDialog(null,"Unable to set up account. " + e1.getMessage());
                }
                }
                else{
                    JOptionPane.showMessageDialog(null, "All fields must be completed in order to set up account");
                }

            }
            else{
                JOptionPane.showMessageDialog(null,"Please select the type of account you want to create.");
            }
        }
    }
    private class RadioButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){


        }
    }

    private class nameFieldListener implements FocusListener{
        public void focusGained(FocusEvent e){

            nameTextField.selectAll();//highlight contents
        }

        public void focusLost(FocusEvent e){
    }



}
    private class initDepositFieldListener implements FocusListener{
        public void focusGained(FocusEvent e){
            initDepositTextField.selectAll();
        }

        public void focusLost(FocusEvent e) {


        }
    }



    public static void main(String[]args){
    GUIaccounts myAccount=new GUIaccounts();
    }   

}

I am trying to create a GUI that allows someone to set up an account. I would like to validate that all the text fields are complete when the create account button is pressed. What is the best way to do this? I am attaching my code but my validation that the text fields are complete is not working.

see code below:

public class GUIaccounts extends JFrame{

private JLabel name;
private JLabel initDeposit;
private JLabel chooseAccount;
private JLabel empty;
private JTextField nameTextField;
private JTextField initDepositTextField;
private JPanel dataPanel;
private JPanel accountTypePanel;
private JRadioButton savingsAccount;
private JRadioButton premiereChecking;
private ButtonGroup radioButtonGroup;
private JButton createAccountButton;
private JPanel createAccountPanel;
private Bank myBank;



public GUIaccounts(){
    setTitle("Create an Account");
    setSize(1000,1000);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    buildPanels();
    setVisible(true);
    pack();
    setLocationRelativeTo(null);
     myBank=new Bank();

}

private void buildPanels(){
    //create the panels
    dataPanel= new JPanel();
    dataPanel.setLayout(new GridLayout(2,2));
    accountTypePanel=new JPanel();
    accountTypePanel.setLayout(new GridLayout(3,1));
    createAccountPanel=new JPanel();
    createAccountPanel.setLayout(new FlowLayout());
    //create labels
    name=new JLabel("Enter Name:");
    Border border = LineBorder.createBlackLineBorder();
    name.setBorder(border);
    initDeposit=new JLabel("Enter Initial Deposit:");
    initDeposit.setBorder(border);
    chooseAccount=new JLabel("Choose Account:");
    empty=new JLabel(" ");
    //create text fields
    nameTextField=new JTextField();
    initDepositTextField=new JTextField();
    //create buttons
    savingsAccount = new JRadioButton("Savings Account");
    premiereChecking =new JRadioButton ("Premiere Checking Account");
    createAccountButton=new JButton("Create Account");
    //add labels and field to the panel
    dataPanel.add(name);
    dataPanel.add(nameTextField);
    dataPanel.add(initDeposit);
    dataPanel.add(initDepositTextField);
    //add button to the panel
    accountTypePanel.add(chooseAccount);
    accountTypePanel.add(empty);
    accountTypePanel.add(savingsAccount);
    accountTypePanel.add(premiereChecking);
    createAccountPanel.add(createAccountButton);

    //add actionListeners to the buttons
    savingsAccount.addActionListener(new RadioButtonListener());
    premiereChecking.addActionListener(new RadioButtonListener());
    createAccountButton.addActionListener(new createAccountListener());
    //add focus to the text field
    nameTextField.addFocusListener(new nameFieldListener());
    initDepositTextField.addFocusListener(new initDepositFieldListener());
    //add panels to the contentPane
    add(dataPanel, BorderLayout.NORTH);
    add(accountTypePanel, BorderLayout.CENTER);
    add(createAccountPanel, BorderLayout.SOUTH);
    //group radio buttons
    radioButtonGroup= new ButtonGroup();
    radioButtonGroup.add(savingsAccount);
    radioButtonGroup.add(premiereChecking);
}
    private class createAccountListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            String name=null;
            Double amount=null;
            if (savingsAccount.isSelected()){
                name=nameTextField.getText();
                amount=Double.valueOf(initDepositTextField.getText());
                if(name!=null && amount !=null){
                try{

                    SavingsAccount account=new SavingsAccount(name,AccountIDs.getNextID(), amount);
                    myBank.addAccount(account);
                    JOptionPane.showMessageDialog(null,"Account setup was successful" + myBank.toString());
                }



                catch(Exception e1){
                    JOptionPane.showMessageDialog(null,"Unable to set up account. " +e1.getMessage());
                }
            }
                else{
                    JOptionPane.showMessageDialog(null, "All fields must be completed in order to set up account");
                }
            }

            else if(premiereChecking.isSelected()){
                name=nameTextField.getText();
                amount=Double.valueOf(initDepositTextField.getText());
                if(name!=null && amount!=null){
                try{
                    PremiereCheckingAccount account=new PremiereCheckingAccount(name, AccountIDs.getNextID(),amount);
                    myBank.addAccount(account);
                    JOptionPane.showMessageDialog(null,"Account setup was successful" +myBank.toString());
                }
                catch(Exception e1){
                    JOptionPane.showMessageDialog(null,"Unable to set up account. " + e1.getMessage());
                }
                }
                else{
                    JOptionPane.showMessageDialog(null, "All fields must be completed in order to set up account");
                }

            }
            else{
                JOptionPane.showMessageDialog(null,"Please select the type of account you want to create.");
            }
        }
    }
    private class RadioButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){


        }
    }

    private class nameFieldListener implements FocusListener{
        public void focusGained(FocusEvent e){

            nameTextField.selectAll();//highlight contents
        }

        public void focusLost(FocusEvent e){
    }



}
    private class initDepositFieldListener implements FocusListener{
        public void focusGained(FocusEvent e){
            initDepositTextField.selectAll();
        }

        public void focusLost(FocusEvent e) {


        }
    }



    public static void main(String[]args){
    GUIaccounts myAccount=new GUIaccounts();
    }   

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

卷耳 2024-11-23 00:46:41

getText() 方法不会返回 null。它将返回空字符串(“”)。

你的测试应该是这样的:

if ( textField.getText().trim().length() == 0 )
  // error

The getText() method will not return null. It will return the empty String ("").

Your test should be something like:

if ( textField.getText().trim().length() == 0 )
  // error
嘦怹 2024-11-23 00:46:41

老问题,但创建一个“验证”帮助器方法通常是一个好主意,该方法首先执行所有验证,然后如果它检查出来,您可以将所有值加载到您正在做的任何事情中(变量,用于实例化某些内容的类属性, ETC)。

例如:

private class createAccountListener implements ActionListener
{
  public void actionPerformed(ActionEvent ae)
  {
    // first we validate all fields... if they pass, we do
    // the rest of the code, otherwise we let the failed validation
    // code tell user what happened, and skip the rest of the code
    if ( validateFields() )
    {
      String fname = fieldFirstName.getText();
      String lname = fieldFirstName.getText();
      int    age   = fieldAge.getText();
    }
  }
}

// test all text fields for input 
public boolean validateFields()
{
  if (! validateField( fieldFirstName, "Please enter a first name")
    return false;
  else
  if (! validateField( fieldLastName, "Please enter a last name")
    return false;
  else
  if (! validateInteger( fieldAge, "Please enter an age greater then 0")
    return false;
  else
    return true;
}

// test if field is empty
public boolean validateField( JTextField f, String errormsg )
{
  if ( f.getText().equals("") )
    return failedMessage( f, errormsg );
  else
    return true; // validation successful
}

public boolean validateInteger( JTextField f, String errormsg )
{
  try
  {  // try to convert input to integer
    int i = Integer.parseInt(f.getText());

    // input must be greater then 0
    // if it is, success
    if ( i > 0 )
      return true; // success, validation succeeded
   }
   catch(Exception e)
   {
      // if conversion failed, or input was <= 0,
      // fall-through and do final return below
   }
   return failedMessage( f, errormsg );
}

public boolean failedMessage(JTextField f, String errormsg)
{
  JOptionPane.showMessageDialog(null, errormsg); // give user feedback
  f.requestFocus(); // set focus on field, so user can change
  return false; // return false, as validation has failed
}

Old question, but it's generally a good idea to create a "validation" helper method that does all the validation first, then if it checks out you can load all the values into whatever you're doing (variables, class attributes to instantiate something, etc).

eg:

private class createAccountListener implements ActionListener
{
  public void actionPerformed(ActionEvent ae)
  {
    // first we validate all fields... if they pass, we do
    // the rest of the code, otherwise we let the failed validation
    // code tell user what happened, and skip the rest of the code
    if ( validateFields() )
    {
      String fname = fieldFirstName.getText();
      String lname = fieldFirstName.getText();
      int    age   = fieldAge.getText();
    }
  }
}

// test all text fields for input 
public boolean validateFields()
{
  if (! validateField( fieldFirstName, "Please enter a first name")
    return false;
  else
  if (! validateField( fieldLastName, "Please enter a last name")
    return false;
  else
  if (! validateInteger( fieldAge, "Please enter an age greater then 0")
    return false;
  else
    return true;
}

// test if field is empty
public boolean validateField( JTextField f, String errormsg )
{
  if ( f.getText().equals("") )
    return failedMessage( f, errormsg );
  else
    return true; // validation successful
}

public boolean validateInteger( JTextField f, String errormsg )
{
  try
  {  // try to convert input to integer
    int i = Integer.parseInt(f.getText());

    // input must be greater then 0
    // if it is, success
    if ( i > 0 )
      return true; // success, validation succeeded
   }
   catch(Exception e)
   {
      // if conversion failed, or input was <= 0,
      // fall-through and do final return below
   }
   return failedMessage( f, errormsg );
}

public boolean failedMessage(JTextField f, String errormsg)
{
  JOptionPane.showMessageDialog(null, errormsg); // give user feedback
  f.requestFocus(); // set focus on field, so user can change
  return false; // return false, as validation has failed
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文