0

I wrote some code that plots coordinates onto a drawing area (JPanel). here is my code class:

class POSCanvas extends JPanel {
    private XYSeries pnts = new XYSeries("Position");

    public POSCanvas() {
        final ChartPanel chartPanel = createDemoPanel();
        this.add(chartPanel, BorderLayout.CENTER);
    }

    private void update(double xnew, double ynew) {
        pnts.add(new XYDataItem(xnew, ynew));
    }

    private ChartPanel createDemoPanel() {
        JFreeChart jfreechart = ChartFactory.createScatterPlot(
            "", "X", "Y", createSampleData(),
            PlotOrientation.VERTICAL, true, true, false);
        XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
        XYItemRenderer renderer = xyPlot.getRenderer();
        NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
        int minX = (int)pnts.getMinX(); int maxX = (int)pnts.getMaxX();
        if (minX < maxX){domain.setRange(minX, maxX);}
        domain.setTickUnit(new NumberTickUnit(1));
        NumberAxis range = (NumberAxis) xyPlot.getRangeAxis();
        range.setTickUnit(new NumberTickUnit(1));
        return new ChartPanel(jfreechart){
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
    }

    private XYDataset createSampleData() {
        XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
        xySeriesCollection.addSeries(pnts);
        return xySeriesCollection;
    }
}

The problem is that I can not seem to add the range for the X axis. Here is the output: enter image description here

I am using the domain.setRange() method but it does not work. Any idea how to fix it? Any help would be appreciated; thank you.

Catalina Island
  • 7,027
  • 2
  • 23
  • 42

1 Answers1

2

Try ChartFactory.createScatterPlot(), which "uses an XYPlot instance as the plot, with a NumberAxis for the domain axis, a NumberAxis as the range axis, and an XYLineAndShapeRenderer as the renderer." Several complete examples are shown here, and the factory's source is included in the distribution.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045