Adding a ChartPanel to JPanel

2019-07-13 11:32发布

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?

2条回答
你好瞎i
2楼-- · 2019-07-13 12:19

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.

查看更多
男人必须洒脱
3楼-- · 2019-07-13 12:26

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?

查看更多
登录 后发表回答