Java AWT Window 没有重新绘制

Java AWT Window doesn't get repainted

我从 window 派生了一个 class,但是每当我调用 setValue()(调用重绘)时,它都不会重绘(调用了该方法,但没有任何变化屏幕)。绘制第一个值,默认为 0。 这是 class:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Window;

@SuppressWarnings("serial")
public class HashtagLikeDisplay extends Window {

    protected int count;

    HashtagLikeDisplay() throws HeadlessException {
        super(null);

        this.setAlwaysOnTop(true);
        this.setBounds(this.getGraphicsConfiguration().getBounds());
        this.setBackground(new Color(0, true));
        this.setVisible(true);
    }

    public void paint(Graphics g) {
        super.paint(g); // Doesn't matter if this is here or not

        Font font = getFont().deriveFont(48f);
        g.setFont(font);
        g.setColor(Color.RED);
        String message = "Total: " + Integer.toString(count);
        g.drawString(message, 10, 58);
    }

    public void update(Graphics g) {
        paint(g);
    }

    public void setCount(int c) {
        this.count = c;
        this.revalidate();
        this.repaint();
    }
}

为什么没有正确重绘?

来自 oracle 文档

If [the update] method is reimplemented, super.update(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, update() will not be forwarded to that child.

此外,正如第一个评论者所说,在 paint() 中调用 super.paint(g)。

如果还是不行,你应该使用 Swing,比如 JComponent 而不是 window。

public class HashtagLikeDisplay extends JComponent {
...

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // Customize after calling super.paintComponent(g)

    Font font = getFont().deriveFont(48f);
    g.setFont(font);
    g.setColor(Color.RED);
    String message = "Total: " + Integer.toString(count);
    g.drawString(message, 10, 58);
  }
}