I'm trying to add Labels to a awt panel from a thread, and I'm calling repaint from the thread, but the panel isn't updating, and only updates when I resize the window. I tried many solutions, but none are working, so please help.
public class Updater extends Thread{
private Panel p;
public Updater(Panel p) {
this.p = p;
}
public void run() {
while (true) {
p.add(new Label("Text"), BorderLayout.NORTH);
p.repaint();
System.out.println("Dodao");
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
public class Main extends Frame {
public Panel p;
private void populateWindow() {
p = new Panel();
p.setLayout(new GridLayout(0, 1));
add(p);
}
public Main() {
setSize(1000, 500);
setResizable(true);
setTitle("Test");
populateWindow();
addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setVisible(true);
}
public static void main(String[] args) {
Main m = new Main();
Updater u = new Updater(m.p);
u.start();
}
}
CodePudding user response:
Use revalidate()
instead of repaint()
. Revalidate()
is used for components, repaint()
is not.