Drawing in Java without JPanel

I am writing a graphical user interface for plotting data along the xy axis. It is written in Java Swing, so I have a JFrame that contains the entire GUI. One component of the GUI is JPanel , which makes up the area where data is displayed. I use Graphics2D for drawing.

I am trying to make a command line extension of this program. The idea is that the user can specify the data that they want to build in the configuration file. This allows for interesting estimates of parameters that save a lot of time.

The problem occurs when I try to get a Graphics object to draw with. I create a JPanel that does the drawing, but the Graphics object is null when I call paintComponent() .

In addition, when you run the program (from the command line again), it steals focus from everything you are trying to do (if this program is running in the background). Is there anyway to get around this? Do you need to create a JPanel for drawing?

Thanks for the help!

PS When I say that I run the program from the command line, I want to say that you are not using a graphical interface. All graphs, etc. Performed without an interface. In addition, I know that you cannot instantiate a Graphics object.

+4
source share
2 answers

Use 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); 
+5
source

If you are not using a graphical interface, you need to use the headless color mode. This will provide you with the correct graphical environment. You will have to either execute with a parameter such as

 java -Djava.awt.headless=true 

or Set a property in your main class, for example:

System.setProperty ("java.awt.headless", "True");

Please see the link for more programmatic examples.

+3
source

Source: https://habr.com/ru/post/1314494/


All Articles