0

I am doing exercises to learn programming in Java. I created a main class where I simply generate random numbers and add each number in an array list. Every time I insert a new number in the array list, I calculate the average of the array list which changes.

I am stuck at the following part: I want to display live on a JFrame each time I calculate a new average (every time a random number is added). I created a JFrame and a JLabel for that. JLabel then needs to be constantly updated.

What directions do I need to go to from there? Swing worker? Swing timer? Action listener? I read a few posts already on the necessity to have it run in the background, multiple threads but I am a bit lost now so any help will be appreciated.

public class TestSwing {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    TestFrame frame = new TestFrame(); 
    frame.setBounds(300, 200, 700, 400);

    // Variables
    Random rn = new Random();
    ArrayList<Integer> elements = new ArrayList<>();

    //Generate random numbers
    for(int i =0; i < 100; i++)
    {
        int answer = rn.nextInt(10) + 1;

        // Add random numbers to array
        elements.add (answer);

            //Get average of array every time a new number is added to the array
            int sum = 0;
            for(int j=0; j < elements.size() ; j++)
            {
                sum = sum + elements.get(j); 
            }
            //calculate average value
            double average = sum / elements.size();

   //Show Frame
   frame.setVisible(true);
   // This is where I am stuck
    }      
} 

}

Aurax22
  • 111
  • 3
  • 13

2 Answers2

2

A java.util.Timer is simple and will do well. Please read this and this for more information.

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Timer().scheduleAtFixedRate(new TimerTask() {
    int counter = 0;

    @Override
    public void run() {
        counter++;
        if (counter >= 10) { // If ran 10 times, stop.
            this.cancel();
        }
        int answer = rn.nextInt(10) + 1;
        elements.add(answer);
        int sum = 0;
        for (int j = 0; j < elements.size(); j++) {
            sum = sum + elements.get(j);
        }
        double average = sum / elements.size();
        label.setText(String.valueOf(average)); // Set the text of the
                                                // label (automatically
                                                // repaints panel)
        System.out.println(String.valueOf(average));
    }
}, 500, 1000); // Run every second (= 1000 milliseconds), wait 500
                // milliseconds before starting it.
Community
  • 1
  • 1
Lukas Rotter
  • 4,158
  • 1
  • 15
  • 35
  • Thanks Luxxminer, I will try working with that and post the result! – Aurax22 Sep 22 '15 at 16:23
  • @Aurax22 There is no need to post an additional answer to your own question. Just accept the answer that helped you the most and actually solved your problem. I'm not begging for the green tick, it's just the way you *should* do it. :P Feel free to let me know if I should post the whole code, btw. – Lukas Rotter Sep 22 '15 at 16:35
0

You left out quite a few things. Here is a better version of your code, you will need to add a timer like LuxxMiner suggested.

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

public class TestSwing {

/**
 * @param args the command line arguments
 */

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setBounds(300, 200, 700, 400);

        //Set layout
        frame.setLayout(new BorderLayout());


        // Variables
        Random rn = new Random();
        ArrayList<Integer> elements = new ArrayList<>();

        //Generate random numbers
        for(int i =0; i < 100; i++)
        {
            int answer = rn.nextInt(10) + 1;

            // Add random numbers to array
            elements.add (answer);

                //Get average of array every time a new number is added to the array
                int sum = 0;
                for(int j=0; j < elements.size() ; j++)
                {
                    sum = sum + elements.get(j); 
                }
                //calculate average value
                double average = sum / elements.size();
        }  
        //Add label
        JLabel label = new JLabel(String.valueOf(average));
        frame.add(label, BorderLayout.CENTER);

        //Show Frame
        frame.setVisible(true);   
} 
}
feltersnach
  • 406
  • 3
  • 20