简体   繁体   中英

Java Swing how to display graphics component inside JPanel

I have an app with the following layout: 在此处输入图像描述

After I click the next screen button, it will hide all the components and several pie and bar charts should appear.

All this code is in my GUI class, then I have a different class, called the PieChart class similar to this which generates the chart using the Java Graphics How can I call this class and display the graph inside a Panel or inside my frame? Thank you!

If the PieChart extends a component then it can simply be placed into a panel for example chartPanel.add(chart); , then you can use a card layout or you can manually toggle visibility as mentioned in the comments. Here is a basic example of changing the visibility of components:

JFrame frame = new JFrame("Demo");
JPanel mainPanel = new JPanel();
JPanel chartPanel = new JPanel();
JButton button = new JButton("View Chart");

frame.add(mainPanel);
frame.add(chartPanel);
mainPanel.add(button);
chartPanel.setVisible(false);

//Add event to create asd show the pie chart
button.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e)
    {
        //Remove any previous chart
        chartPanel.removeAll();

        //Create and add new chart based on data
        PieChart chart = new PieChart(yourData);
        chartPanel.add(chart);
    
        //Hide the main panel with the buttons, and show the chart panel instead
        chartPanel.setVisible(true);
        mainPanel.setVisible(false);
    }
});

Note that you would need to add another button to the chartPanel so that you can swap back to the main panel if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM