[英]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? All this code is in my
GUI
class, then I have a different class, called the PieChart PieChart
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);
如果 PieChart 扩展了一个组件,那么它可以简单地放入一个面板中,例如
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.请注意,您需要向 chartPanel 添加另一个按钮,以便在需要时可以切换回主面板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.