gpt4 book ai didi

java - JFreechart:将图表面板的所有组件保存在 png 文件中

转载 作者:行者123 更新时间:2023-12-02 01:05:26 24 4
gpt4 key购买 nike

使用JFree我想制作一个XY图,并在图外的右边距中写入一些信息...并将所有内容(即图+信息)保存在一个png文件中。我想我找到了一种使用以下代码来做到这一点的方法:

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;

public class example {

public static void main(String[] args) {

XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series =new XYSeries("data");
series.add(1, 1);
series.add(2, 2);
series.add(3, 3);
series.add(4, 4);
dataset.addSeries(series);

// create the chart...
final JFreeChart chart = ChartFactory.createXYLineChart(
"Example plot",
"X AXIS",
"Y AXIS",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);


int plotWidth = 500;
int leftMargin = 70;
int rightMargin = 400;

final XYPlot plot = chart.getXYPlot();
// change margin size
AxisSpace axisSpace=new AxisSpace();
axisSpace.setRight(rightMargin);
axisSpace.setLeft(leftMargin);
plot.setFixedRangeAxisSpace(axisSpace);


// add text outside the plot area
Box b = new Box(BoxLayout.Y_AXIS);
b.setBorder(new EmptyBorder(50, plotWidth+leftMargin, 100, 210));
JLabel label = new JLabel();
label.setText("I want to add some");
b.add(label);
label = new JLabel();
label.setText("information about the plot");
b.add(label);
label = new JLabel();
label.setText("here outside the graph");
b.add(label);

ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500+400, 500));
chartPanel.add(b);
JFrame container = new ApplicationFrame("");
container.setContentPane(chartPanel);
container.pack();
container.setVisible(true);


}

}

当绘图显示在框架中时,我得到以下结果:

enter image description here

但是,当我保存它时(执行 dosave、doprint、另存为、或通过缓冲图像),我得到以下结果:

enter image description here

有没有办法将图表面板的所有组件都包含在我的 png 文件中?是否有另一种方法可以将信息放在右边距中并将完整结果保存在 png 文件中?

感谢您的关注。

最佳答案

performing a dosave, or a doprint, or a save as

我对 JFreeChart API 提供的方法一无所知,所以我不知道这些方法是如何工作的。

但是,对我来说,“chartPanel”似乎是添加到框架中的唯一组件。因此,如果您创建“chartPanel”的图像,您应该获得添加到框架中的所有内容的图像。

创建任何组件图像的基本代码是:

Dimension d = component.getSize();
BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
component.print( g2d );
g2d.dispose();
ImageIO.write(image, ".jpg", new File(...));

或者,您可以查看Screen Image一个允许您创建任何 Swing 组件图像的类。

关于java - JFreechart:将图表面板的所有组件保存在 png 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60103739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com