Java 图形,未显示任何内容

Java graphics, nothing shows up

我可能正在做一些非常愚蠢的事情并且看不到它,但我一直在尝试为用于条形图的矩形调整大小设置动画。代码符合要求,但我的框架中没有显示任何内容。完全空白。

    package server2;

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Bar extends JPanel implements Runnable {

    int height = 0;
    Color barColor;
    Rectangle bar;
    Thread bartender;

    public Bar(int x, int y, Color barColor) {
        this.barColor=barColor;
        this.bar = new Rectangle(x, y, 15, this.height);
        this.bartender= new Thread(this);
    }

    public void update() {
        bar.setSize(this.bar.width, this.bar.height++);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(this.barColor);
        g2d.fill(this.bar);
    }

    public void callBarTender() {
        this.bartender.notify();
    }

    @Override
    public void run() {
        for(int i = this.bar.height; i<this.height; i++ ) {
            try {
                update();
                repaint();
                Thread.sleep(30);
            } catch(Exception e) {
                System.out.println(e);
            }
        }
        try {
            this.bartender.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Bar bar1 = new Bar(200,200, Color.blue);
        bar1.setVisible(true);
        frame.add(bar1);
        bar1.height = 10;
        bar1.bartender.start();

    }

改变...

bar.setSize(this.bar.width, this.bar.height++);

bar.setSize(this.bar.width, this.bar.height + 1);

bar.setSize(this.bar.width, ++this.bar.height);

this.bar.height++ 的赋值是一个 post 赋值,它被忽略了

你也应该调换这两行的顺序...

bar1.setVisible(true);
frame.add(bar1);

所以 setVisible 在您准备好 UI 之后被调用。

您还应该考虑使用 Swing Timer,它可以更安全地更新 UI 或 UI 可能依赖于绘画的任何数据