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

前端 未结 1 1001
死守一世寂寞
死守一世寂寞 2020-12-22 02:05
class GraphGenerator1 extends JPanel {
    ChartPanel chartPanel, sbc;

    void generator(int t, int Value1, int Value2) {
        if (t == 1) {
            Default         


        
相关标签:
1条回答
  • 2020-12-22 03:04

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题