Skip to content
Advertisement

Java AWT Window doesn’t get repainted

I’ve derived a class from window, but whenever I call setValue() (which calls repaint) it doesn’t get redrawn (the method is called, but nothing changes on the screen). The first value is drawn, which is 0 by default. Here’s the 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();
    }
}

Why does it not get repainted properly?

Advertisement

Answer

From the oracle docs

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.

Also, call super.paint(g) in paint() just as the first commenter said.

If it still doesn’t work, you should use Swing, like a JComponent instead of 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);
  }
}
Advertisement