0

I've tried looking for answers to get this but it didn't work properly so here goes my question. I have created a barchart and I want to add this to a jpanel in a java swing application , here is my code for adding chart to the panel,

void addpanel(JFreeChart chart) {

ChartPanel chartpanel = new ChartPanel(chart);
jPanel2.setLayout(new BorderLayout());
jPanel2.add(chartpanel, BorderLayout.CENTER);
chartpanel.setVisible(true);
this.add(jPanel2);
this.pack();
setContentPane(jPanel2);
jPanel2.setVisible(true);

}

but when I run this , chart is not visible in the jpanel2 and it don't give any errors. How can I change this code to make it work ?

1 Answers1

1

I'm guessing that your program extends JFrame or ApplicationFrame.

  • A ChartPanel is a JPanel , so you don't need jPanel2 at all.

  • The default layout of JFrame is BorderLayout, and the default location is BorderLayout.CENTER.

  • Call pack() after you add the contents to the frame.

  • Call setVisible() last; you shouldn't have to call it for anything inside.

    void addPanel(JFreeChart chart) {
        ChartPanel chartPanel = new ChartPanel(chart);
        this.add(chartPanel); //BorderLayout.CENTER
        this.pack();
        this.setVisible(true);
    }
    
Catalina Island
  • 7,027
  • 2
  • 23
  • 42