-1

I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:

public class RandomMathGame extends JFrame {

public RandomMathGame(){
    super("Random Math Game");
    int random2;
    JButton lvl1 = new JButton("LEVEL 1");
    JButton lvl2 = new JButton("LEVEL 2");
    JButton lvl3 = new JButton("LEVEL 3");
    JLabel line1 = new JLabel("Line 1: ");
    final JTextField jtf1 = new JTextField(10);
    JLabel line2 = new JLabel("Line 2: ");
    final JTextField jtf2 = new JTextField(10);
    JLabel result = new JLabel("Result: ");
    final JTextField jtf3 = new JTextField(10);
    JButton ans = new JButton("Answer");
    JLabel score = new JLabel("Score: ");
    JTextField jtf4 = new JTextField(3);
    JLabel itm  = new JLabel("Number of Items: ");
    JTextField items = new JTextField(3);
    FlowLayout flo = new FlowLayout();
    setLayout(flo);
    add(lvl1);
    add(lvl2);
    add(lvl3);
    add(line1);
    add(jtf1);
    add(line2);
    add(jtf2);
    add(result);
    add(jtf3);
    add(ans);
    add(score);
    add(jtf4);
    add(itm);
    add(items);
    setSize(140,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    lvl1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            int i, j = 10;
            int i1 = Integer.valueOf(jtf1.getText());
            int i2 = Integer.valueOf(jtf2.getText());
            int i3 = i1 + i2;
            final int random1 = (int)(Math.random() * 10 + 1);

            for (i = 0; i <= j + 1; i++){
                try{
                    jtf1.setText(String.valueOf(random1));
                    jtf2.setText(String.valueOf(random1));
                    jtf3.setText(String.valueOf(i3));
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    });
}

Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)

jhenryj09
  • 45
  • 8

1 Answers1

1

Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045