I have a bar chart which I want to update and I tried the revalidate and repaint methods but with no success

老子叫甜甜 提交于 2019-11-29 16:57:38
trashgod

Your approach works after a fashion. A better solution is to update the chart's model, gData, and let the chart update itself. Also,

  • Don't use a mouse listener on a JButton; just handle the ActionEvent.

  • Use Java naming conventions.

  • A JOptionPane can have multiple inputs fields, as shown here.

SSCCE:

public class GraphFrame extends JFrame {

    GraphFrame() {
        final GraphPanel gPanel = new GraphPanel();
        gPanel.create();
        JButton button = new JButton(new AbstractAction("Update") {
            @Override
            public void actionPerformed(ActionEvent e) {
                String a = JOptionPane.showInputDialog(rootPane,
                    "ENTER FIRST VALUE", "", JOptionPane.PLAIN_MESSAGE);
                String b = JOptionPane.showInputDialog(rootPane,
                    "ENTER SECOND VALUE", "", JOptionPane.PLAIN_MESSAGE);
                int aa = Integer.parseInt(a);
                int bb = Integer.parseInt(b);
                gPanel.update(aa, bb);
            }
        });
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.add(gPanel, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    private static class GraphPanel extends JPanel {

        private DefaultCategoryDataset gData = new DefaultCategoryDataset();

        void create() {
            update(56, 20);
            JFreeChart chart = ChartFactory.createBarChart("", "", "", gData,
                PlotOrientation.VERTICAL, false, false, false);
            ChartPanel chartPanel = new ChartPanel(chart);
            this.add(chartPanel);
        }

        private void update(int value1, int value2) {
            gData.clear();
            gData.setValue(value1, "What you saved", "");
            gData.setValue(value2, "What you paid", "");
        }
    }

    public static void main(String args[]) {
        new GraphFrame();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!