Doszi89
Doszi89

Reputation: 357

Adding a ChartPanel to JPanel

I've got some not working code here:

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, true, true, true);
    ChartPanel chartpanel = new ChartPanel(chart);

    chartpanel.setDomainZoomable(true);
    jPanel4.setLayout(new BorderLayout());
    jPanel4.add(chartpanel, BorderLayout.NORTH);

So the problem is that the jPanel4 with a chart is not visible. When I add my chartpanel to a frame and make it visible, it works.

Anyone knows what's my mistake?

Upvotes: 2

Views: 13994

Answers (2)

brimborium
brimborium

Reputation: 9522

This works perfectly fine for me:

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class Main {
    public static void main(String[] args) {
        XYSeries series = new XYSeries("asdf");
        for (int i = 0; i < 100; i++)
            series.add(i, Math.random());
        XYSeriesCollection dataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, true, true, true);
        ChartPanel chartpanel = new ChartPanel(chart);
        chartpanel.setDomainZoomable(true);

        JPanel jPanel4 = new JPanel();
        jPanel4.setLayout(new BorderLayout());
        jPanel4.add(chartpanel, BorderLayout.NORTH);

        JFrame frame = new JFrame();
        frame.add(jPanel4);
        frame.pack();
        frame.setVisible(true);
    }
}

Can you provide us with a bit more code? Do you put something else into jPanel4? There can not be more than one component in every spot (NORTH, SOUTH, WEST, EAST, CENTER). Do you put your panel into a frame?

Upvotes: 6

vels4j
vels4j

Reputation: 11298

do u have anything in CENTER Layout in jpanel else try adding chart in center

ChartPanel chartpanel = new ChartPanel(chart);
chartpanel.setDomainZoomable(true);
jPanel4.add(chartpanel, BorderLayout.CENTER);

NORTH is actually top of the container.

Upvotes: 1

Related Questions