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
}
}
}