如何解决当JTextField内容不等于某个int时显示消息
我正在弄清楚每当用户不在JTextField中键入数字7时如何显示消息对话框。
这是我在按钮单击事件中尝试的代码:
try {
Double user_input = Double.parseDouble(myTextField.getText());
while (user_input !=7) {
JOptionPane.showMessageDialog(null,"Please type number 7","Error",JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
}
解决方法
将事件监听器添加到按钮上对我来说很有效
public static void main(String[] args) {
{
final JFrame f= new JFrame("TextField Example");
final JTextField textField;
textField=new JTextField("");
textField.setBounds(50,150,200,30);
f.add(textField);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int value = Integer.parseInt(textField.getText());
if(value!=7) {
JOptionPane.showMessageDialog(f,"Number should be 7.","Dialog",JOptionPane.ERROR_MESSAGE);
}
}
});
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
,
我尝试了您的代码。如果我输入的数字不是7,则输入JTextField
会起作用。如果输入字母,则不会显示弹出警告。我认为当您键入字母而不是数字时,它不起作用。
这是东西:try ... catch
块用于捕获exception
。如果键入数字,则double.parseDouble
将起作用,因此exception
块中将没有try
被捕获,并且如果{{1}中的条件出现,您将看到警告消息。 }没有遇到。
如果键入字母,则while
将引发异常,因为不允许将字母转换为双精度。它会跳到double.parseDouble
块来处理异常,而不是移到下一行(while循环),但是您没有指定处理方法,也不会看到任何警告消息。>
因此,解决方案很简单:在catch
引发异常时,向catch
块添加一个操作以执行某些操作,例如显示一条消息:
double.parseDouble
您可能会注意到,使用try
{
Double user_input = Double.parseDouble(jTextField1.getText());
while (user_input != 7)
{
JOptionPane.showMessageDialog(null,"Please type number 7","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Please type numbers",JOptionPane.ERROR_MESSAGE);
}
会继续显示警告消息,因为条件始终是while
,输入不是7。因此请更改为true
作为@Hades回答或添加{{ 1}},使其仅显示1次。
我更喜欢if
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。