I am trying to align the whole chart within a JFrame but the normal component codes that I know do not work for JChartPanels. Initially I tried to setAligmentX and Y on the JChartPanel but that didn't work. I then tried to add the JChartPanel to a JPanel then setAlignment but once I add the JChartPanel to a JPanel the graph is no longer visible.
The code below creates a graph within a JFrame at the default top left location. I need to align the graph- use any values as I will change them later to fit my purpose.
The contained code without any of the attempts(errors) mentioned above:
import java.awt.*;
import javax.swing.*;
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.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class ChartTest extends javax.swing.JFrame {
public ChartTest() {
XYSeries Goals = new XYSeries("Goals Scored");
Goals.add(1, 1.0);
Goals.add(2, 3.0);
Goals.add(3, 2.0);
Goals.add(4, 0.0);
Goals.add(5, 3.0);
XYDataset xyDataset = new XYSeriesCollection(Goals);
JFreeChart chart = ChartFactory.createXYLineChart("Goals Scored Over Time", "Fixture Number", "Goals", xyDataset, PlotOrientation.VERTICAL, true, true, false);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.PAGE_AXIS));
jPanel.setVisible(true);
jPanel.setSize(300, 300);
ChartPanel CP = new ChartPanel(chart) {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
CP.setMouseWheelEnabled(true);
add(CP);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChartTest().setVisible(true);
}
});
}