How to display JFreeChart in a NetBeans project

This is similar to the question I asked yesterday, but more specific to the problem. What is the correct method to add JFreeChart to a NetBeans project that already contains various widgets? My updateChart () hides the whole JFrame. I would like to add JFreeChart in a JFrame.

public class MyClass extends javax.swing.JFrame implements TableModelListener { public MyClass() { initComponents(); ... updateChart(); } private void updateChart() { XYDataset dataset = createXYdataset(); JFreeChart chart = createChart(dataset); JPanel chartPanel = new ChartPanel(chart); setContentPane(chartPanel); } private XYDataset createXYdataset() { XYSeries series = new XYSeries(""); int rows = jTable.getRowCount(); if (rows > 0) { int ms = 0; for (int row = 0; row < rows; row++) { series.add(ms, 1); ms += Integer.parseInt( jTable.getValueAt(row, PULSE_ON).toString()); series.add(ms, 1); series.add(ms, 0); ms += Integer.parseInt( jTable.getValueAt(row, PULSE_OFF).toString()); series.add(ms, 0); } } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); return dataset; } private JFreeChart createChart(XYDataset dataset) { JFreeChart chart = ChartFactory.createXYLineChart( null, // chart title "ms", // x axis label null, // y axis label dataset, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls ); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainPannable(true); plot.setRangePannable(true); plot.setRangeGridlinesVisible(false); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); return chart; } } 

Corrected Code:

 private void updateChart() { XYDataset dataset = createXYdataset(); JFreeChart chart = createChart(dataset); JPanel chartPanel = new ChartPanel(chart); chartPanel.setSize(jPanel1.getSize()); jPanel1.add(chartPanel); jPanel1.getParent().validate(); } 
+6
java swing netbeans jfreechart
source share
1 answer

My updateChart () hides all JFrame.

 JFreeChart chart = createChart(dataset); JPanel chartPanel = new ChartPanel(chart); setContentPane(chartPanel); 

This would be because you are replacing the contents pane of your frame with the pane of the free chart.

I don’t know which layout manager you are using, but you need to β€œADD” a free chart pane to a panel containing all the other components. Therefore, perhaps when you create a general form in Netbeans, you add a blank panel to the place where you want to add a free chart panel. Then, when you add a free chart pane, the code will look something like this:

 emptyFreeChartPanel.add( chartPanel ); emptyFreeChartPanel.getParent().validate(); 

The check confirms to Swing that the components have been added so that the layout manager will be called.

+8
source share

All Articles