I'm writing a graphical user interface to plot data on a xy-axis. It's written in Java Swing so I have a JFrame
that contains the whole GUI. One of the components of the GUI is a JPanel
that makes up the area where the data is plotted. I use Graphics2D
to do my drawing.
I'm trying to make a command line extension of this program. The idea is that the user can specify the data that they want plotted in a config file. This allows for interesting parameter sweeps that save a lot of time.
The problem occurs when I try to obtain a Graphics
object to draw with. I create the JPanel
that does the drawing, but the Graphics
object is null when I call paintComponent()
.
Also, when you run the program (from command line again), it steals focus from whatever else you're trying to do (if this program is running in the background). Is there anyway to get around that? Do you have to create a JPanel
to do drawing?
Thanks for any help provided!
P.S. When I say that I'm running the program from command line, I mean to say that you are not using the GUI. All of the plotting, etc. is being done without an interface. Also, I'm aware that you can't instantiate a Graphics
object.
Use a java.awt.image.BufferedImage
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
//.. draw stuff ..
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
writer.setOutput(ImageIO.createImageOutputStream(new File("myimage.png"));
writer.write(image);
If you are not using GUI, you need to use headless mode This will provide you proper graphics environment. You will have to either execute with an option such as
java -Djava.awt.headless=true
or Set property in your main class such as:
System.setProperty("java.awt.headless", "true");
Please check out the link for more programmatic examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With