简体   繁体   English

在Java Swing组件中劫持`repaint()`调用

[英]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. 我正在编写一个在无头环境中运行的应用程序,需要输出到BufferedImage而不是屏幕。 I have a Display class managing the BufferedImage . 我有一个管理BufferedImageDisplay类。 My app extends JPanel and in order to make it automatically repaint when a component updates, I've re-implemented repaint() as: 我的应用程序扩展了JPanel ,为了在组件更新时自动重绘,我重新实现了repaint()

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 . 但是,每当我启动我的应用程序时,我会在尝试绘制到Display NullPointerException时收到NullPointerException This is supposedly some code in the JPanel constructor that tries to repaint. 这应该是JPanel构造函数中尝试重绘的一些代码。 The problem is that getDisplay() returns null. 问题是getDisplay()返回null。 However, the Display has already been instantiated and passed to the app at this point. 但是, Display已经实例化并在此时传递给应用程序。 I've verified this by having the Display print out its own properties on creation, before sending it to the app. 我已经通过让Display在创建时打印出自己的属性,然后再将其发送到应用程序来验证这一点。

The exception is as follows; 例外情况如下; the topmost location refers to the line containing getDisplay() : 最顶部的位置是指包含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. 编辑:我研究了这个,但找不到满意的分辨率。

nidu told it first, but since he doesn't answer I put it. nidu首先告诉它,但是因为他不回答我说的。

Probably you're calling super() in the constructor method, and the JPanel constructor is trying to repaint before the display has been set. 可能你在构造函数方法中调用了super(),并且JPanel构造函数在设置显示之前尝试重绘。

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

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