添加一个限制器,如果将错误的数字插入到 java 中的文本字段,则会出现错误

Adding a limiter that gives an error if a wrong number is insertd to a textfield in java

我有一个带有图形用户界面的代码数据库,如果用户输入未指定的代码,我喜欢它给用户一个礼貌的错误。(0 到 30 范围之外)我应该怎么做那?这是我到目前为止编写的代码。

public class koodibaasiteinetäiustus extends JFrame {

private static final long serialVersionUID = 1L;
private JTextField tfCount;
public koodibaasiteinetäiustus() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    setResizable(false); 
    cp.add(new JLabel("enter code"));
    tfCount = new JTextField ("0", 10);
    tfCount.setEditable(true);
    cp.add(tfCount);
    JButton nupp = new JButton("give answer");
    cp.add(nupp);
    cp.add(new JLabel("zero equals text"));
    nupp.addActionListener(new ActionListener() {
            @Override
        public void actionPerformed(ActionEvent evt) {
            String[] array;
            array = new String[31];
            array[0] = "text";
            array[1] = "643201";
            array[2] = "643202";
            array[3] = "643203";
            array[4] = "643204";
            array[5] = "643205";
            array[6] = "643206";
            array[7] = "643207";
            array[8] = "643208";
            array[9] = "643209";
            array[10] = "643210";
            array[11] = "643211";
            array[12] = "643212";
            array[13] = "643213";
            array[14] = "643214";
            array[15] = "643215";
            array[16] = "643216";
            array[17] = "643217";
            array[18] = "643218";
            array[19] = "643219";
            array[20] = "643220";
            array[21] = "643221";
            array[22] = "643222";
            array[23] = "643223";
            array[24] = "643224";
            array[25] = "643224";
            array[26] = "643226";
            array[27] = "643227";
            array[28] = "643228";
            array[29] = "643229";
            array[30] = "643230";

            int number = Integer.parseInt(tfCount.getText());
            tfCount.setText(String.valueOf(array[number]));

        }

    });
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Koodibaas");
    setSize(300, 100);
    setVisible(true);
}

public static void main(String[] args) {
             SwingUtilities.invokeLater(new Runnable() {
                 @Override
                 public void run() {
                    new koodibaasiteinetäiustus();
                 }
             });
}
}

that is not specified.(outside the area of 0 to 30)

使用允许您指定数字范围的 JSpinner

阅读有关 How to Use Spinners 的 Swing 教程部分,了解更多信息和示例。

我不明白这个问题,你不能只使用 if 吗?

if( numeber>=0 && number<=30) {
    ...
} else {
    error
}

您还可以在将其转换为 int 时检查格式,如果用户插入的不是数字,则会出现异常:

try { 
    number = Integer.parseInt(tfCount.getText());
} catch (NumberFormatException e) {
    error
}