Netbeans: JPanel in designer mode with code behind.

I wanted to add a JPanel to my palette so I could easily include it into a JFrame, in designer mode that is.

This was the constructor of my JPanel:

/** Creates new form SetupPanel */
public SetupPanel()
{
	super();
	this.initComponents();

	this.jTextFieldDataDirectory.setText(Main.getProperties().getProperty(Settings.DATADIRECTORY));
	this.jTextFieldOpenSSLLocation.setText(Main.getProperties().getProperty(Settings.OPENSSLLOCATION));
}

This gave me a nice error when I added it to the panel:

The component cannot be instantiated. Please make sure it is a JavaBeans component.

This is because when you add it to the palette Netbeans compiles the class, and at that point it cannot find ‘Main’, so it throws a NullPointer.

Surrounding those statements with Beans.isDesignTime() solves the problem:

/** Creates new form SetupPanel */
public SetupPanel()
{
	super();
	this.initComponents();

	if (!Beans.isDesignTime())
	{
		this.jTextFieldDataDirectory.setText(Main.getProperties().getProperty(Settings.DATADIRECTORY));
		this.jTextFieldOpenSSLLocation.setText(Main.getProperties().getProperty(Settings.OPENSSLLOCATION));
	}
}

Now you can add it to the palette without problems.

This entry was posted in Java, Netbeans. Bookmark the permalink.