Reputation: 370
I'm trying to show in a JPanel how an algorythm fills a matrix, step by step.
The thing is I just learnt Thread.Sleep(number)
actually freezes the GUI and I don't think I can use Swing Timers for this. So I ran out of ideas.
First, I've got a JPanel1 which has a JTextField and a Button. When the button is pressed, a extra frame is created with JPanel2 in it, which will hold the representation of the table with it's size determined by the number in the previous text field. This is all handled by my Control class.
Public class Control implements ActionListener
{
JPanel1 panel;
public Control(JPanel1 vista)
{
this.panel = vista;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Push"))
{
int num = panel.getNumber();
if(((num & (num - 1)) != 0) || num == 1 || num == 0)
{
panel.isError();
}
else
{
panel.clean();
JPanel2 panel2 = new JPanel2(num);
JFrame window = new JFrame("Tournament");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane( (JPanel) panel2);
window.pack();
window.setVisible(true);
Tournament t = new Tournament (num,panel2);
t.init();
}
}
}
Tournament is the class that holds the method with the algorythm. I passed the panel2 object as an argument to "Tournament" so that the init()
method ,which contains the algorythm, will be the one to update the panel.
public void init()
{
for(int i=0;i < this.matrix.length;i++)
{
for(int j = 0; j < matrix[i].length; j++)
{
matrix[i][j] = 0;
panel2.setCell(matrix[i][j],i,j);
}
}
}
The setCell(int x, int y, int z)
method changes the value of the components on JPanel2 depending on the row and column number.
So how can I make the changes appear progressively? I mean making the program wait everytime it calls the setCell
method.
Upvotes: 0
Views: 87
Reputation: 324118
You can use a SwingWorker
to contain your looping code and then inside the loop you can "publish" the value that is to be used to update the GUI. In the process()
method of the SwingWorker
you can use Thread.sleep(...).
Read the section from the Swing tutorial on Concurrency for more information and working examples.
If you want to use a Swing Timer, you will need to restructure you code a little. Basically every time the Timer fires you would increment the "j" variable. When "J" is greater than the max, you reset it back to "0" and increment the "I" variable. Then you update the cell and invoke repaint().
Upvotes: 4