简体   繁体   English

在没有JPanel的情况下使用Java绘图

[英]Drawing in Java without a JPanel

I'm writing a graphical user interface to plot data on a xy-axis. 我正在编写一个图形用户界面来绘制xy轴上的数据。 It's written in Java Swing so I have a JFrame that contains the whole GUI. 它是用Java Swing编写的,所以我有一个包含整个GUI的JFrame One of the components of the GUI is a JPanel that makes up the area where the data is plotted. GUI的一个组件是JPanel ,它构成了绘制数据的区域。 I use Graphics2D to do my drawing. 我使用Graphics2D来绘图。

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. 当我尝试获取要绘制的Graphics对象时,会发生此问题。 I create the JPanel that does the drawing, but the Graphics object is null when I call paintComponent() . 我创建了绘图的JPanel ,但是当我调用paintComponent()时, Graphics对象为null。

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? 你必须创建一个JPanel来绘图吗?

Thanks for any help provided! 感谢您提供的任何帮助!

PS When I say that I'm running the program from command line, I mean to say that you are not using the GUI. PS当我说我从命令行运行程序时,我的意思是说你没有使用GUI。 All of the plotting, etc. is being done without an interface. 所有的绘图等都是​​在没有界面的情况下完成的。 Also, I'm aware that you can't instantiate a Graphics object. 另外,我知道你无法实例化Graphics对象。

Use a java.awt.image.BufferedImage 使用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. 如果您不使用GUI,则需要使用无头模式这将为您提供适当的图形环境。 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"); System.setProperty(“java.awt.headless”,“true”);

Please check out the link for more programmatic examples. 请查看链接以获取更多程序化示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM