Search code examples
javaswingjfreechart

Add horizontal scroll to JFreeChart


As the title says: how can I add horizontal scrollbar to my candlestick chart I created with the JFreeChart? I want the user to be able to scroll horizontally through the chart when zoomed in. Right now the zooming in works but I can't move left or right. I tried putting ChartPanel into JScrollPane but that's a chartpanel, not the chart itself. My custom ChartPanel constructor:

public MyChartPanel(JFreeChart chart) {
    super(chart);
    lineDrawingControllers =new EventListenerList();
    this.setMouseZoomable(false);
    this.addMouseListener(mouseHandler);
    this.addMouseMotionListener(mouseHandler);
    this.setPopupMenu(null);
    this.linePopupMenu=new JPopupMenu();
    linePopupMenuListener=new LinePopupMenuListener();
}

My custom Jpanel where I create the Chart and ChartPanel and put the ChartPanel inside the JScrollPane:

public MyCandleStickChart() {
    ohlcSeries = new OHLCSeries("Test data");
    ohlcSeriesCollection = new OHLCSeriesCollection();
    ohlcSeriesCollection.addSeries(ohlcSeries);
    ohlcSeries=ohlcSeriesCollection.getSeries(0);

    chart= ChartFactory.createCandlestickChart("Default Chart", "Time", "Value", ohlcSeriesCollection, true);
    chart.getXYPlot().setOrientation(PlotOrientation.VERTICAL);
    chartPanel=new MyChartPanel(chart);
    chartPanel.setDisplayToolTips(false);
    jScrollPane=new JScrollPane(chartPanel);
    jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(jScrollPane);
    add(tooltipPanel);
}

Then I add the MyCandleStickChart JPanel to the main application frame:

myCandleStickChart=new MyCandleStickChart();
applicationFrame.add(myCandleStickChart, BorderLayout.CENTER);

Solution

  • You can actually move it left and right if you call setDomainPannable(true) on XYPlot. Looks like chart.getXYPlot().setDomainPannable(true) in your case. There is also a method setRangePannable(boolean pannable) for panning in range direction respectively. When I used it long time ago, this resulted in being able to move chart by dragging the middle mouse button. I don't know what the behavior will be in your case nowadays :) But this method is a good place to start if you have no other ideas. May be if you look inside the source code there, then you can create your own custom scrollbar for the same functionality.

    Upd.: Alternatively, you can just increase/decrease the size of ChartPanel by yourself on mouse wheel or whatever without using zooming functionality of JFreeChart. Then JScrollPane will do the job. Which is fine and easier if you just want to scale globally. But if you want that nice zooming of user selected area, then I would look into customizing of JFreeChart's "panning".

    Upd2.: I might be wrong about middle mouse button. Probably it was CTRL + mouse dragging like in the link provided by @trashgod