Monday, 29 December 2008

How do I get my netbeans drag and drop widget to know whether it is rendering inside the netbeans design view window or the running application?

Question: Why would you want this?

Answer: In case you are doing custom animation that will go outside the bounds of the component.

This is how:

public void paintComponent(Graphics g) {
super.paintComponent(g);
if (super.getRootPane().getParent() instanceof JFrame) {
Component c = javax.swing.SwingUtilities.getRoot(this);
String className = c.getClass().getCanonicalName();
if (!"org.netbeans.core.windows.view.ui.MainWindow".equalsIgnoreCase(className)) {
JFrame parentFrame = (JFrame) super.getRootPane().getParent();
...
}else {
// Inside Netbeans demo window
}
}
}


----
Addenum
----
This is a simpler way I've just been made aware of:

java.beans.Beans.isDesignTime()

Here is an example of it in use:

package test;

import java.awt.Graphics;
import java.beans.Beans;

import javax.swing.JLabel;

public class TestLabel extends JLabel {
private static final long serialVersionUID = -2438507032083091628L;

public TestLabel() {
super();
}

public void paint(Graphics g) {
super.paint(g);

if (Beans.isDesignTime())
this.setText("Design Time");
else
this.setText("Production runtime");
}
}