打开新文件时刷新图表

Refreshing chart when a new file is opened

我必须表示从文件选择器返回到图表的数据。一切正常,直到我再次按下按钮并选择不同的文件。问题是它没有表示新数据集,而是将其添加到前一个数据集。我尝试了 revalidaterepaintremove 方法,但没有任何效果(或者我不知道将这些方法放在哪里。

我的代码如下所示:

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() 方法可能允许您重用现有实例;对于其他人,创建一个新实例可能更容易。