Java 在 JFrame 中包括两个以上的面板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2528888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Including more than two Panels in a JFrame?
提问by Neethu
We are working on a project where we encountered a problem with including more than two Panels on the same JFrame .What we want is one Panel above the other.
我们正在处理一个项目,在该项目中我们遇到了在同一个 JFrame 上包含两个以上面板的问题。我们想要一个面板在另一个上面。
Can the community help give an example of ho to implement this or refer me to a good tutorial or guide related to our Java Swing needs?
社区能否帮助提供一个示例来实现这一点,或者向我推荐与我们的 Java Swing 需求相关的好的教程或指南?
回答by bragboy
Assuming you want two panels added to a single frame:
假设您希望将两个面板添加到单个框架中:
Set a layout for your parent JFrame and add the two panels. Something like the following
为您的父 JFrame 设置布局并添加两个面板。类似于以下内容
JFrame frame = new JFrame();
//frame.setLayout(); - Set any layout here, default will be the form layout
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel1);
frame.add(panel2);
Assuming you want to add one panel over the other
假设您想在另一个面板上添加一个面板
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel1);
panel1.add(panel2);
There is no limit on the number of panels to be added on the JFrame. You should understand that they all are containers when seen on a higher level.
在 JFrame 上添加的面板数量没有限制。你应该明白,在更高的层次上看,它们都是容器。
回答by Wintermut3
if you want each of the frames/panels the same size, use the GridLayout, with a grid of 1(column) and 2(rows)
如果您希望每个框架/面板的大小相同,请使用 GridLayout,网格为 1(列)和 2(行)
Frame myFrame;
GridLayout myLayout = new GridLayout(2,1);
myFrame.setLayout(myLayout);
Panel p1;
Panel p2;
myFrame.add(p1);
myFrame.add(p2);
if the panels are different size use the BorderLayout.... set the upper frame to "North" and the lower one to "South" or "Center"
如果面板大小不同,请使用 BorderLayout .... 将上框设置为“北”,将下框设置为“南”或“中心”
Frame myFrame;
myFrame.setLayout(new BorderLayout() );
Panel p1;
Panel p2;
myFrame.add(p1, BorderLayout.NORTH);
myFrame.add(p2, BorderLayout.CENTER);
回答by Ashish kudale
//you can also use card Layout, that enables you to add multiple card-panels on Main panel.
//您还可以使用卡片布局,这使您可以在主面板上添加多个卡片面板。
CardLayout cl;
JPanel main,one,two,three;
JButton button1,button2;
cl = new CardLayout();
main.setLayout(cl);
main.add(one,"1");
main.add(two,"2");
main.add(three,"3");
cl.show(main,"1");
public void actionPerformed(ActionEvent e){
if(e.getSource() == button1)
cl.show(main,"2");
else if(e.getSource() == button2)
cl.show(main,"3");
}