将ChartPanel添加到JPanel

时间:2012-09-07 12:49:52

标签: java netbeans jpanel jfreechart

我这里有一些不工作的代码:

    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);

所以问题是带有图表的jPanel4不可见。当我将图表面板添加到框架并使其可见时,它可以正常工作。

任何人都知道我的错误是什么?

2 个答案:

答案 0 :(得分:5)

这对我来说非常好:

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);
    }
}

您能为我们提供更多代码吗?你把其他东西放到了jPanel4吗?每个点(NORTH, SOUTH, WEST, EAST, CENTER)中不能有多个组件。你把面板放在一个框架里吗?

答案 1 :(得分:1)

你在CENTER jpanel中的布局中有什么内容吗,请尝试在中心添加图表

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

NORTH实际上是容器的顶部。