[英]try and catch exceptions with jtextfield?
我正在制作一個簡單的GUI,其中用戶必須輸入2個隨機數字字符串,並且在按下完成按鈕時,它將輸出這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());
}
}
isDigit(char)
方法可能對您有用。
public void actionPerformed(ActionEvent e)
{
for(char c: field1.getText().toCharArray()) {
if(!Character.isDigit(c)) throw new WhateverException();
}
//Repeat this for field2's text as well
//do other things with the strings, at this point they are valid
}
將WhateverException
替換為您需要在此處引發的任何異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.