2011-10-30 100 views
10

如果我有我的Jpanel和我的JFreeChart。我如何將此圖表添加到JPanel?添加JFreeChart到JPanel

XYSeries series = new XYSeries("XYGraph"); 
    series.add(1, 1); 
    series.add(1, 2); 
    series.add(2, 1); 
    series.add(3, 9); 
    series.add(4, 10); 

// Add the series to your data set 
    XYSeriesCollection dataset = new XYSeriesCollection(); 
    dataset.addSeries(series); 

// Generate the graph 
    JFreeChart chart = ChartFactory.createXYLineChart(
    "XY Chart", // Title 
    "x-axis", // x-axis Label 
    "y-axis", // y-axis Label 
    dataset, // Dataset 
    PlotOrientation.VERTICAL, // Plot Orientation 
    true, // Show Legend 
    true, // Use tooltips 
    false // Configure chart to generate URLs? 
); 

現在,我該如何在我的JPanle中添加圖表?

回答

20

從舊java forums thread

JPanel jPanel1 = new JPanel(); 
jPanel1.setLayout(new java.awt.BorderLayout()); 
.. 
ChartPanel CP = new ChartPanel(chart); 
.. 
jPanel1.add(CP,BorderLayout.CENTER); 
jPanel1.validate(); 
1
JFreeChart chart = new JFreeChart("Cos(x) and Cos^2(x) versus x", parent); 
ChartPanel myChart = new ChartPanel(chart); 
myChart.setMouseWheelEnabled(true); 
jPanel1.setLayout(new java.awt.BorderLayout()); 
jPanel1.add(myChart,BorderLayout.CENTER); 
jPanel1.validate(); 
0

我有同樣的問題,但我能夠確定的方式來解決這個問題。

JPanel panel = new JPanel(); 
 
\t \t panel.setBackground(new Color(255, 102, 51)); 
 
\t \t panel.setBounds(50, 64, 955, 888); 
 
\t \t frame.getContentPane().add(panel); 
 
\t \t panel.setLayout(null); //Absolute Layout 
 

 
XYSeries series = new XYSeries("XY Chart"); 
 
\t \t XYSeriesCollection dataset = new XYSeriesCollection(series); 
 
\t \t JFreeChart chart = ChartFactory.createTimeSeriesChart("Testing Chart", "Date", "Average Profit", dataset); 
 
\t \t 
 
\t \t ChartPanel chartPanel = new ChartPanel((JFreeChart) null); 
 
\t \t chartPanelH2S.setChart(chart); 
 
\t \t chartPanelH2S.setBounds(39, 193, 419, 309); 
 
\t \t panel.add(chartPanel); 
 
frame.setVisible(true);

希望這有助於