JFreeChart简单图(抛物线)

时间:2013-11-19 20:54:38

标签: java jfreechart

我使用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个坐标)。怎么做?如何用新系数重建情节?

1 个答案:

答案 0 :(得分:4)

如果ChartMouseEvent名为cmd,则忽略任何类型的实体其他而不是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)