簡體   English   中英

如何嘗試使用jtextfield捕獲異常?

[英]how to try and catch exceptions with jtextfield?

我正在做一個簡單的GUI,用戶必須輸入2個隨機數字字符串,然后按“完成”按鈕將輸出這2個字符串。 但是,我該如何使用try-catch方法來做到這一點,以便用戶只能使用數字,否則它將捕獲異常?

這是我的代碼:

import java.awt.event.*;
import javax.swing.*;

public class Panel extends JPanel 
{
    private JTextField field1;
    private JTextField field2;
    private JButton button1;
    private JLabel label1;
    private JLabel label2;

    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());
        }
    }
}

提前致謝

//You save yor recieved string from textfield and try to convert it to an integer
//If is not convertable, it throws an exception and prints in console the error
String string1 = field1.getText();
int myInteger = 0;
try {
    myInteger = Integer.parseInt(string1);
} catch(Exception e){
    System.out.println("Invalid input. Not an integer");
    e.printStackTrace();
}

希望能有所幫助。 問候。

您在這里有兩個選擇。 第一個也是推薦的方法使用JFormattedTextField ,以消除獲得NumberFormatException的機會。 另外,它更加人性化。

第二種選擇是捕獲NumberFormatException ,並在捕獲時向用戶添加一種“錯誤”消息(不是那么用戶友好),並告訴他提供正確的輸入。 然后,他未按一下字母,我們回到了錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM