在无头调用新的JPanel()时的NPE(RepaintManager.currentManager)

时间:2016-10-13 12:01:37

标签: java swing nullpointerexception headless jsvc

我正在运行一个带openjdk-8-jdk-armhf的无头linux盒子,当我运行我的应用程序时,该行

METRICS = new JPanel().getFontMetrics(FONT);

抛出NullPointerException,返回RepaintManager.currentManager(RepaintManager.java:262),如下所示:

    public static RepaintManager currentManager(Component c) {
       // Note: DisplayChangedRunnable passes in null as the component, so if
       // component is ever used to determine the current
       // RepaintManager, DisplayChangedRunnable will need to be modified
       // accordingly.
       return currentManager(AppContext.getAppContext());
    }

完整跟踪如下:

java.lang.NullPointerException
    at javax.swing.RepaintManager.currentManager(RepaintManager.java:262)
    at javax.swing.JComponent.repaint(JComponent.java:4799)
    at java.awt.Component.repaint(Component.java:3303)
    at javax.swing.JComponent.setFont(JComponent.java:2756)
    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:664)
    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 lukemoll.MyClass.<init>(MyClass.java:15)

我可以通过jsvcjava命令重现此错误。

1 个答案:

答案 0 :(得分:0)

感谢Gyro Gearless指出this answer

  

这个(Canvas)也可以在无头模式下工作。

我最终使用new Canvas().getFontMetrics(font);,我不知道上次我是如何让它工作的,但这可以在我的机器上工作(tm)。