JLabel java中变量的后期更新

时间:2017-03-23 16:18:06

标签: java jframe actionlistener

我在actionPerformed的代码中遇到了问题。代码应该显示2个标签和一个文本字段,我的问题是标签q = new JLabel(x + " x " + y)显示上一个操作执行的x和y,意味着标签的x和y落后一步,我试着操纵这个地方标签,但我找不到解决方案,我只需要用x和y的当前值更新标签。这是我的代码..

public class Multiplication extends JFrame implements ActionListener {
/**
 * 
 */
private static final long serialVersionUID = 5551059254300001091L;
private int x, y, z, i;
private JLabel q, w;
private JTextField a;
    public Multiplication(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        q = new JLabel(x + " x " + y);
        w = new JLabel("Score = 0");
        a = new JTextField(5);
        add(q);
        add(a);
        add(w);
        pack();
        setVisible(true);
        a.addActionListener(this);
    }

@Override
public void actionPerformed(ActionEvent e) {
    Random random = new Random();
    x = random.nextInt(10) + 1;
    y = random.nextInt(10) + 1;
    q.setText(x + " x " + y);
    z = x*y;
    int s = Integer.parseInt(a.getText());
    if(s == z){
        w.setText("Score = "+ i++);
    }
    else{
        JOptionPane.showMessageDialog(null, "Correct answer is: " + z);
    }
}
public static void main(String[] args){
    new Multiplication();
}

}

1 个答案:

答案 0 :(得分:1)

在您阅读输入之前,您似乎正在更改x和y的值。如果你用生成新数字的行来切换检查输入的行,它应该可以工作。

public void actionPerformed(ActionEvent e) {
    int s = Integer.parseInt(a.getText());
    if(s == z){
        w.setText("Score = "+ i++);
    }
    else{
        JOptionPane.showMessageDialog(null, "Correct answer is: " + z);
    }

    Random random = new Random();
    x = random.nextInt(10) + 1;
    y = random.nextInt(10) + 1;
    q.setText(x + " x " + y);
    z = x*y;
}