I have the bellow code which call data from MySQL and return in a XYPlot (JFreeChart) on a JPanel. There are different datasets, depending of the row index of my JTable. The problem is when I select a row, the chart seems to be good, but when I select another row, the XYplot appear but when I make a click (drag, second mouse-click, etc.) the chart returns to the first one. Practically every time when I select another plot, and I make something with the mouse (zooming, etc.), it returns to the primary/first xyplot selection.
I tried JPanel.validate(); but still not working, also repaint(); method. Furthermore, with JFrame it is working very good, no problem (yes! right, because opens every time one frame with the specific XYPlot). I suppose that the problem is from JPanel. Any help/advice? Please!
UPDATE: The JPanel with the XYPlot, is encapsulated in an JSplitPanel. When I move the divider (enlarge JPanel with the XYPlot), there are two XYPlot, the first one (obtained on the first click, and the second one (if was clicked second time to another row/dataset -> XYPlot). I suppose that the problem is from query -> and repainting over the previous XYPlot.
private void PrimaryTableMouseClicked(java.awt.event.MouseEvent evt) {
int row = PrimaryTable.getSelectedRow();
int realIndex = PrimaryTable.convertRowIndexToModel(row);
String Table_click = (PrimaryTable.getModel().getValueAt(realIndex, 0).toString());
try {
String query = "select wavenumber,spectrum FROM test where id_test ='" + Table_click + "'";
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
if (rs.next()) {
JDBCXYDataset dataset = new JDBCXYDataset(ConnecrDb(), query);
JFreeChart chart = ChartFactory.createXYLineChart(
"title",
"cm",
"in",
dataset,
PlotOrientation.VERTICAL,
false, //legend
true, //tooltip
false); //urls
XYPlot plot = (XYPlot) chart.getPlot();
ChartPanel CP = new ChartPanel(chart);
PanelWithChart.setLayout(new BorderLayout());
PanelWithChart.add(CP, BorderLayout.CENTER);
PanelWithChart.repaint();
}
rs.close();
pst.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
I think that this may be your problem
By calling
JPanel#add()you are adding a new component each timePrimaryTableMouseClickedis called. If yourChartPanelis the only component onPanelWithCharttry removing the previous chart:This will not work if you have other components on the panel, if this is the case then you will need to use
PanelWithChart.remove(Component comp)but this is harder as you do not have a referance to the previous chart.Please not that this is probably not the best way the use a chart, have you considered creating the chart once and making the
dataseta propery? You could then use this code inPrimaryTableMouseClickedto achieve much the effect.