Questo è simile a una domanda che ho chiesto ieri ma più specifica al problema. Qual è il metodo corretto per aggiungere un JFreeChart a un progetto NetBeans che contiene già vari widget? My updateChart() nasconde l'intero JFame. Vorrei aggiungere JFreeChart a JFrame.Come visualizzare un JFreeChart in un progetto NetBeans
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;
}
}
codice corretto:
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();
}
L'IDE NetBeans sembra utilizzare un GroupLayout per LayoutManager. Ho aggiunto un JPanel chiamato jPanel1 al progetto e 'jPanel1.add (chartPanel); jPanel1.getParent() convalida().; e jPanel1.setVisible (true); 'to' updateChart() 'ma il grafico non è visibile in jPanel1. Altre idee? – jacknad
GroupLayout richiede l'uso di vincoli che non conosco. Immagino che il problema sia che il pannello vuoto ha una dimensione preferita di 0, quindi i contrappesi non sono impostati correttamente per aggiungere un altro componente. Costruisco sempre i miei layout GUI a mano così ho il pieno controllo del layout. Quindi il mio suggerimento sarebbe di imparare come usare i gestori di layout e fare la codifica da soli, quindi non sei dipendente dall'IDE. – camickr
Grazie mille per l'indizio. Tutto ciò di cui aveva bisogno era un 'chartPanel.setSize (jPanel1.getSize());'. – jacknad