【发布时间】:2019-08-02 04:06:23
【问题描述】:
我正在制作一个简单的 GUI,用户必须输入 2 个随机数字字符串,当按下 done 按钮时,它将输出这 2 个字符串。但是如何使用 try-catch 方法做到这一点,以便用户只能使用数字,否则它会捕获异常?
这是我的代码:
public Panel()
{
label1 = new JLabel("first string: ");
label2 = new JLabel("second string: ");
field1 = new JTextField(38);
field2 = new JTextField(3);
button1 = new JButton("done");
ButtonP buttonP = new ButtonP();
button1.addActionListener(buttonP);
this.add(label1);
this.add(field1);
this.add(label2);
this.add(field2);
this.add(button1);
}
private class ButtonP implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("String 1 " + field1.getText() + " and string 2 " + field2.getText());
}
}
【问题讨论】:
-
您可以查看
JTextField的属性,有一个选项可以禁用字段中的字符输入(即只输入数值)
标签: java swing user-interface