您好,我需要一些帮助来验证我的 gui 中的文本字段。我的教授给了我如何做的提示,但它冻结了我的程序。我尝试了其他方法,但是如果我输入文本,则下一个窗口不会显示。
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.*;
//import statements here
public class UserWindow extends JFrame
{
private JTextField nameField, ageField, creditCardField;
private JButton backButton, nextButton;
public UserWindow()
{
super("Please enter your information");
setSize(700,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4,2));
buildPanel();
setVisible(true);
}
private void buildPanel(){
nameField = new JTextField(10);
ageField = new JTextField(2);
creditCardField = new JTextField(10);
backButton = new JButton("Back");
nextButton = new JButton("Next");
nextButton.addActionListener(new NextButton());
backButton.addActionListener(new BackButton());
JLabel NameLabel = new JLabel("Please enter your name");
JLabel ageLabel = new JLabel("Enter your age");
JLabel creditCardLabel = new JLabel("Enter your credit card number");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
add(panel6);
add(panel7);
add(panel8);
panel1.add(NameLabel);
panel2.add(nameField);
panel4.add(ageField);
panel6.add(creditCardField);
panel3.add(ageLabel);
panel5.add(creditCardLabel);
panel7.add(backButton);
panel8.add(nextButton);
}//end of panel building
//action listeners for fields/buttons
private class NextButton implements ActionListener{
public void actionPerformed(ActionEvent e){
String str;
int age;
str = nameField.getText();
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
if(e.getSource() == nextButton)
new MovieSelection();
setVisible(false);
}
}
private class BackButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == backButton)
setVisible(false);
new SelectUserWindow();
}
}
}