Ryan Kennedy
Ryan Kennedy

Reputation: 3615

Hijack `repaint()` call in Java Swing component

I'm writing an app which runs in a headless environment and needs to output to a BufferedImage instead of a screen. I have a Display class managing the BufferedImage. My app extends JPanel and in order to make it automatically repaint when a component updates, I've re-implemented repaint() as:

public void repaint(){
    Graphics2D g = getDisplay().getGraphics();
    paint(g);
    getDisplay().repaint();
}

Whenever I start up my app, though, I get a NullPointerException when it tries to draw to the Display. This is supposedly some code in the JPanel constructor that tries to repaint. The problem is that getDisplay() returns null. However, the Display has already been instantiated and passed to the app at this point. I've verified this by having the Display print out its own properties on creation, before sending it to the app.

The exception is as follows; the topmost location refers to the line containing getDisplay():

Exception in thread "main" java.lang.NullPointerException
    at com.mypapyri.clay.ui.App.repaint(App.java:28)
    at javax.swing.JComponent.setFont(JComponent.java:2746)
    at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:208)
    at javax.swing.plaf.basic.BasicPanelUI.installDefaults(BasicPanelUI.java:66)
    at javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:56)
    at javax.swing.JComponent.setUI(JComponent.java:655)
    at javax.swing.JPanel.setUI(JPanel.java:153)
    at javax.swing.JPanel.updateUI(JPanel.java:126)
    at javax.swing.JPanel.<init>(JPanel.java:86)
    at javax.swing.JPanel.<init>(JPanel.java:109)
    at javax.swing.JPanel.<init>(JPanel.java:117)
    at com.mypapyri.clay.ui.App.<init>(App.java:18)
    at ClayOS.<init>(ClayOS.java:22)
    at ClayOS.main(ClayOS.java:84)

EDIT: I've researched this and could not find a satisfactory resolution.

Upvotes: 4

Views: 190

Answers (1)

raven1981
raven1981

Reputation: 1445

nidu told it first, but since he doesn't answer I put it.

Probably you're calling super() in the constructor method, and the JPanel constructor is trying to repaint before the display has been set.

Upvotes: 1

Related Questions