JFreeChart not appearing on JPanel - may be something to do with my code's logic

一曲冷凌霜 提交于 2019-12-05 15:24:48

The chart itself is largely irrelevant, except that it

  1. Has some preferred size.

  2. Has been added to a Container having a suitable layout.

In the sscce below, a mock player panel and chart panel are added to a GridLayout(1, 0). The ChartPanel is given an arbitrary size by overriding getPreferredSize().

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
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;

/**
 * @see http://stackoverflow.com/a/16828209/230513
 */
public class Test {

    private static final int N = 128;
    private static final Random random = new Random();

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel(new GridLayout(1, 0));
        p.add(createPlayerPanel());
        p.add(createChartPanel());
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private ChartPanel createChartPanel() {
        final XYSeries series = new XYSeries("Data");
        for (int i = 0; i < random.nextInt(N) + N / 2; i++) {
            series.add(i, random.nextGaussian());
        }
        XYSeriesCollection dataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createXYLineChart("Test", "Domain",
            "Range", dataset, PlotOrientation.VERTICAL, false, false, false);
        return new ChartPanel(chart) {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(N * 2, N * 2);
            }
        };
    }

    private Box createPlayerPanel() {
        Box b = new Box(BoxLayout.Y_AXIS);
        b.setBorder(new EmptyBorder(10, 10, 10, 10));
        for (int i = 0; i < 16; i++) {
            JLabel label = new JLabel();
            label.setAlignmentX(0.5f);
            String s = String.valueOf(label.hashCode());
            label.setText(s + ": " + s);
            b.add(label);
        }
        return b;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}

Try to create the graph on its own JPanel then add it to your existing project.

Also look at the jpanel layout and make sure you are using the most appropriate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!