Search code examples
javaswinglook-and-feeljappletuimanager

UIManager.getColor returns null sometimes


I have an applet that is generating a nullpointer exception at this line (but only sometimes) at load time:

(txtpnNoSeHa is a JEditorPane inside a class that extends JPanel. This panel is instantiated inside the applet constructor)

txtpnNoSeHa.setBackground(UIManager.getColor("Panel.background"));

called inside the constructor.

What I understand from this is that UIManager.getColor returns null sometimes maybe because some data has not been loaded (no swing panel has been shown or something similar)

The applet was designed with eclipse's window builder. How can I fix this? Any one can shed some light into this?


Solution

  • As you had predicted, the UIManager is loaded as soon the first swing component is made visible. This may lead to null values. You can manually load the UIManager with this call at the beginning of the main routine (or init for applets):

    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(InvocationTargetException | UnsupportedLookAndFeelException e) {
        e.printStackTrace(); 
    }