我必须将从文件选择器返回的数据表示为图表。一切正常,直到我再次按下按钮并选择不同的文件。问题在于,它不是表示新的数据集,而是将其添加到前一个数据集。我尝试了 revalidate
、repaint
和 remove
方法,但没有任何效果(或者我不知道将这些方法放在哪里。
我的代码如下所示:
JButton theButton = new JButton("Choose the file");
theButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
theFile = fileChooser.getSelectedFile();
try {
ReadGCFile.readGCList(theFile, gcArrayList,
gcStringList, gcDateList);
} catch (NumberFormatException | IOException
| ParseException e) {
System.out.println("Something's wrong.");
}
try {
frame1 = createCharts.createBarChart();
desktopPane.add(frame1);
frame1.pack();
frame1.setVisible(false);
frame1.setBounds(460, 50, 1260, 1000);
frame2 = createCharts.combinedBarAndLineChart();
desktopPane.add(frame2);
frame2.pack();
frame2.setVisible(false);
frame2.setBounds(460, 50, 1200, 1000);
frame3 = createCharts.createGCLineChart();
desktopPane.add(frame3);
frame3.pack();
frame3.setVisible(false);
frame3.setBounds(460, 50, 1200, 1000);
} catch (IOException | ParseException e) {
System.out.println("Something's wrong.");
}
}
//frame1.getContentPane().repaint();
//frame2.getContentPane().repaint();
//frame3.getContentPane().repaint();
}
});
desktopPane.add(theButton);
theButton.setVisible(true);
theButton.setBounds(20, 100, 250, 20);
getContentPane().add(theButton);
有人可以帮我解决这个问题吗?
最佳答案
应该重新考虑这种方法:不要更换组件; 更新它们。如果您更新图表的数据集,监听图将相应更新自身,如图 here 所示。 .
在 DefaultCategoryDataset
的特殊情况下,clear()
方法可能允许您重用现有实例;对于其他人来说,创建一个新实例可能更容易。
关于java - 打开新文件时刷新图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34157849/