在mouseclick上为jfreechart添加点

时间:2017-04-09 07:57:24

标签: java jfreechart

我使用鼠标监听器将数据点添加到JFreechart的XYLineChart系列中,如下所示:

public class ChartTest extends ApplicationFrame implements  
    ChartMouseListener, MouseListener, MouseMotionListener {
  private JFreeChart chart;
  private ChartPanel chartPanel;
  private double chartX;
  private double chartY;
  private XYSeries series = new XYSeries("High");
  private XYSeriesCollection data = new XYSeriesCollection();

  public ChartTest(String title) {
    super(title);
    String chartTitle = " ";

    this.chart = ChartFactory.createXYLineChart(chartTitle, "X", "Y", 
            createDataset(), PlotOrientation.VERTICAL, true, true, false);
    chartPanel = new ChartPanel(this.chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(600, 300));
    chartPanel.setMouseZoomable(true, false);
    chartPanel.addChartMouseListener(this);
    chartPanel.addMouseMotionListener(this);
    chartPanel.addMouseListener(this);

  public XYDataset createDataset() {
      data.addSeries(series);
      return data;
  }

  public void mouseClicked(MouseEvent event) {
    int x = event.getX();
    int y = event.getY();     
    Point2D point = chartPanel.translateScreenToJava2D(new Point(x, y));
    XYPlot plot = (XYPlot) chart.getPlot();

    Rectangle2D bounds = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    chartX = domainAxis.java2DToValue(point.getX(), bounds, 
            domainAxisEdge);
    chartY = rangeAxis.java2DToValue(point.getY(), bounds, 
            rangeAxisEdge);

    series.add(chartX, chartY);
  } 

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            ChartTest test = new ChartTest(
                    "Test");
                test.pack();
                RefineryUtilities.centerFrameOnScreen(test);
                test.setVisible(true);
        }
    });
}

现在我想实现鼠标拖动功能,但我仍然坚持如何实现该部分。任何有关如何开始使用它的帮助都会很棒。 感谢。

0 个答案:

没有答案