如何获取 JTextField 以检查文本是否等于 int

how to get a JTextField to check if the text is equal to an int

我正在制作一个程序,您可以在其中输入一个数字,它会告诉您是对还是错。这是代码。

static int num = 1;

JPanel pnl = new JPanel();
        JTextField numSlot = new JTextField(5);
        pnl.add(new JLabel("Enter the number:"));
        pnl.add(numSlot);

        int k = JOptionPane.showConfirmDialog(null, pnl, "Enter your code", -1);
        if (k == JOptionPane.OK_OPTION) {

            if(numSlot.getText().equals(num)) {
                JOptionPane.showMessageDialog(null, "It Worked", "It Worked", -1);
            } else {
                JOptionPane.showMessageDialog(null, "Sorry", "Sorry", -1);
            }
        }
        if (k == JOptionPane.CANCEL_OPTION) {

        } else {

        }

使用此代码,即使我输入 1,它也总是输出 sorry 是不是我做错了什么?如果可以,你能回答一下吗,不要粗鲁,我是初学者。

使用

if(numSlot.getText().equals(num+"")){

而不是

if(numSlot.getText().equals(num)) {

as num+"" 将其 int 转换为 String。 否则你可以使用 Integer.toString(num)String.valueOf(num)

说明

numSlot.getText() return 字符串和 num 是整数,所以 numSlot.getText().equals(num) 总是假的,因为字符串值不能与整数值相同。