-
Simple GUI problem
Hello all.
Im tring to create a button on panel, and by pressing it, A loop with a 1 sec delay starts. I want each time to change the label in the panel with the index of it.
The problem is that is show only the last changed and not every change in the loop.
attached 2 classes:
run- main
Test- the button
Thank you...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class run extends JFrame
{
public static void main (String[] args) {
JFrame frame=new JFrame ("test");
frame.setResizable(false);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setLocation(100,500); // enter loc
frame.setSize(600,80);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel();
frame.add(panel);
JButton test=new JButton ("Test");
panel.add (test);
test.addActionListener(new Test(panel));
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JPanel _panel;
public Test(JPanel panel){
_panel= panel;
}
public void actionPerformed(ActionEvent e) {
JLabel _text1 =new JLabel();
_panel.add(_text1);
for (int i=1;i<=3;i++){
_text1.setText("current # "+i);
try{
Thread.sleep(1000);
}
catch(Exception s){
System.exit(0);
}
}
}
}
-
Re: Simple GUI problem
There exists a separate Thread, the EDT thread (Event Dispatch Thread); it does all the painting of the visible components as well the dispatching (read: running) of events. If it is running the code in your ActionListener (an event), it can't draw anything and the drawing commands are collected for later (when the EDT has time to draw again).
kind regards,
Jos
-
Re: Simple GUI problem
You need to take turns with the JVM using the EDT thread. When it's your turn you change the label. When it's the JVMs turn it displays the changes you have made.
You can do this by using a Timer. The Timer will give your code its "turn" so it can change the label. When your code in the timer is done and exits, then the JVM can show what you have changed.
-
Re: Simple GUI problem
See: Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)
You can use the Swing worker to create a Thread that loops and then sleeps for a second. Within the loop you can "publish" the counter so that the label can be updated on the GUI.
-
Re: Simple GUI problem
Moved from 'New to Java'
db