I want to change some of my JFrame components(JPanel, ChartPanel) after some action event occured(button clicked). Below a concrete example:
Initially I'm starting my frame empty(only with menu bar and without any other panels). I'm clicking menu 'file > open', choose a file and here become a chart. After that for clarity I've resized my frame. All is perfect. But next I'm clicking choose file again to get new chart and instead of this my chart not properly updated: here is an illustration of problem
And here is my code:
public MenuBarDataAnalyser() {
JMenu menuFile = new JMenu("File");
itmOpen = new JMenuItem("Open...");
itmOpen.addActionListener(this);
add(menuFile);
menuFile.add(itmOpen);
}
@Override
public void actionPerformed(ActionEvent e) {
if(source == itmOpen){
final JFileChooser fch = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("FITS file", "fits");
fch.setFileFilter(filter);
int response = fch.showOpenDialog(itmOpen);
if (response == JFileChooser.APPROVE_OPTION){
String pathFilename = fch.getSelectedFile().toString();
JFreeChart chart = GUIDataAnalyserFrame.createChart(pathFilename);
ChartPanel chartPanel = new ChartPanel(chart, true, true, true, false, true);
JButton button = new JButton("Calibrate");
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
chartPanel.revalidate();
GUIDataAnalyserApp.analyserFrame.add(chartPanel, BorderLayout.CENTER);
GUIDataAnalyserApp.analyserFrame.add(buttonPanel, BorderLayout.EAST);
GUIDataAnalyserApp.analyserFrame.revalidate();
}
}
}
Why this happening and what I need to change?
A guess since you've not posted a valid minimal code example program, but you should remove the old components from the container, then add the new ones, then call revalidate()
THEN call repaint()
-- a critical step which you appear to be missing. The repaint should help clean out old "dirty" pixels.
Or you could go the much easier route and simply use a CardLayout to help you swap views.