简体   繁体   English

Java awt Panel 不会从线程重新绘制,只会在我调整窗口大小时更新

[英]Java awt Panel doesn't repaint from thread and only updates when I resize the window

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.我正在尝试从线程将标签添加到 awt 面板,并从线程调用重绘,但面板没有更新,并且仅在我调整窗口大小时更新。 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();
    }
}

Use revalidate() instead of repaint() .使用revalidate()而不是repaint() Revalidate() is used for components, repaint() is not. Revalidate()用于组件, repaint()不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM