Refreshing chart when a new file is opened

2019-08-11 06:56发布

I have to represent data returned from a file chooser to a chart. Everything works fine until I press the button again and choose a different file. The problem is that instead of representing the new dataset, it's adding it to the previous one. I tried the revalidate, repaint and remove methods, but nothing worked (or I didn't know where to put those methods.

My code looks like this:

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);

Can anybody help me with this?

1条回答
太酷不给撩
2楼-- · 2019-08-11 07:58

This approach should be reconsidered: don't replace components; update them in place. If you update a chart's dataset, the listening plot will update itself in response, as shown here.

image

In the particular case of DefaultCategoryDataset, the clear() method may allow you to reuse the existing instance; for others, it maybe easier to create a fresh instance.

查看更多
登录 后发表回答