gpt4 book ai didi

java - JFreeChart 简单绘图(抛物线)

转载 作者:行者123 更新时间:2023-11-30 07:12:47 29 4
gpt4 key购买 nike

我使用 JFreeChart 写了一个简单的抛物线图。

package parabolademo;

import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.function.Function2D;
import org.jfree.data.function.PolynomialFunction2D;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;


public class ParabolaDemo extends ApplicationFrame {

/*
* @param title the frame title.
*/
public ParabolaDemo(final String title) {

super(title);
double[] a = {0.0, 0.0, 3.0};
Function2D p = new PolynomialFunction2D(a);
XYDataset dataset = DatasetUtilities.sampleFunction2D(p, -20.0, 20.0, 100, "Function");
final JFreeChart chart = ChartFactory.createXYLineChart(
"Parabola",
"X",
"Y",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);

final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.addChartMouseListener(new ChartMouseListener() {

@Override
public void chartMouseClicked(ChartMouseEvent cme) {
Point2D po = chartPanel.translateScreenToJava2D(cme.getTrigger().getPoint());
Rectangle2D plotArea = chartPanel.getScreenDataArea();
XYPlot plot = (XYPlot) chart.getPlot(); // your plot
double chartX = plot.getDomainAxis().java2DToValue(po.getX(), plotArea, plot.getDomainAxisEdge());
double chartY = plot.getRangeAxis().java2DToValue(po.getY(), plotArea, plot.getRangeAxisEdge());
System.out.println("Clicked!");
System.out.println("X:" + chartX + ", Y:" + chartY);
}

@Override
public void chartMouseMoved(ChartMouseEvent cme) {

}
});
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
}

public static void main(final String[] args) {

final ParabolaDemo demo = new ParabolaDemo("Parabola Plot Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}

如何获取 FUNCTION PLOT 点的坐标(我的 chartMouseListener 获取窗口中任意点的坐标)?如何在用户移动鼠标并释放鼠标按钮后接收点坐标?我希望当单击鼠标时,绘图的点跟随鼠标,因此绘图将被重建(为此目的,有必要再次计算系数,知道这个坐标并采用任何 2 个其他坐标)。怎么做到的?如何用新系数重建绘图?

最佳答案

给定一个名为 cmdChartMouseEvent,忽略 other XYItemEntity 之外的任何类型的实体。了解实体后,不要进行插值 - 只需查询数据集即可。

ChartEntity ce = cme.getEntity();
if (ce instanceof XYItemEntity) {
XYItemEntity e = (XYItemEntity) ce;
XYDataset d = e.getDataset();
int s = e.getSeriesIndex();
int i = e.getItem();
System.out.println("X:" + d.getX(s, i) + ", Y:" + d.getY(s, i));
}

还可以考虑在绘图渲染器上调用 setBaseShapesVisible(true)

关于java - JFreeChart 简单绘图(抛物线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081801/

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