How can I convert an Icon to an Image

Just found a code snippet which might help if you want to wrap those misbehaving LAF provided icons more often: /** * Some ui-icons misbehave in that they unconditionally class-cast to the * component type they are mostly painted on. Consequently they blow up if * we are trying to paint them anywhere else (f.i. … Read more

Convert text content to Image

The Graphics 2D API should be capable of achieving what you need. It has some complex text handling capabilities as well. import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class TextToGraphics { public static void main(String[] args) { String text = “Hello”; /* Because … Read more

Is it safe to construct Swing/AWT widgets NOT on the Event Dispatch Thread?

Sun has changed the rules in 2004 — before, you were allowed to create the components outside the EDT and only had to move into the EDT once the component had been realized. The new rule now reads: To avoid the possibility of deadlock, you must take extreme care that Swing components and models are … Read more

Setting java.awt.headless=true programmatically

I was working with a main() in a class which statically loads different parts of JFreeChart in Constants (and other static code). Moving the static loading block to the top of the class solved my problem. This doesn’t work: public class Foo() { private static final Color COLOR_BACKGROUND = Color.WHITE; static { /* too late … Read more

Java – FontMetrics without Graphics

No you do not necessarily need to get/use the graphics object: Font font = new Font(“Helvetica”,Font.PLAIN,12); Canvas c = new Canvas(); FontMetrics fm = c.getFontMetrics(font); If you would now call c.getGraphics() it would return null. The canvas solution on the other hand will also work in headless mode.

tech