import java.awt.*;
import javax.swing.*;
public class Panels extends JApplet
{
private Container c = getContentPane();
public void init()
{
BorderLayout bl = new BorderLayout();
setLayout(bl);
add(new JButton("East "), BorderLayout.EAST);
add(new JButton("West "), BorderLayout.WEST);
add(new JButton("North "), BorderLayout.NORTH);
add(new JButton("South "), BorderLayout.SOUTH);
addCenterPanel();
}
void addCenterPanel()
{
JPanel p = new JPanel();
setLayout(new BorderLayout());
add(new JButton("Right "), BorderLayout.EAST);
add(new JButton("Left "), BorderLayout.WEST);
add(new JButton("Up "), BorderLayout.NORTH);
add(new JButton("Down "), BorderLayout.SOUTH);
addInnermostPanel();
}
void addInnermostPanel()
{
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
add(new JButton("> "), BorderLayout.EAST);
add(new JButton("< "), BorderLayout.WEST);
add(new JButton("^ "), BorderLayout.NORTH);
add(new JButton("v "), BorderLayout.SOUTH);
add(new JButton("O"), BorderLayout.CENTER);
}
}
我希望面板能够在彼此内部显示(在CENTER区域中),但是它们在彼此之上打印,无论出于何种原因我无法弄清楚我缺少的东西。在此先感谢,任何帮助表示赞赏
答案 0 :(得分:2)
这是你的代码应该是这样的;
import java.awt.*;
import javax.swing.*;
public class Panels extends JFrame
{
private Container c = getContentPane();
public void init()
{
BorderLayout bl = new BorderLayout();
setLayout(bl);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
add(new JButton("East "), BorderLayout.EAST);
add(new JButton("West "), BorderLayout.WEST);
add(new JButton("North "), BorderLayout.NORTH);
add(new JButton("South "), BorderLayout.SOUTH);
add(addCenterPanel(),"Center");
}
JPanel addCenterPanel()
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JButton("Right "), BorderLayout.EAST);
p.add(new JButton("Left "), BorderLayout.WEST);
p.add(new JButton("Up "), BorderLayout.NORTH);
p.add(new JButton("Down "), BorderLayout.SOUTH);
p.add(addInnermostPanel(),"Center");
return p;
}
JPanel addInnermostPanel()
{
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
center.add(new JButton("> "), BorderLayout.EAST);
center.add(new JButton("< "), BorderLayout.WEST);
center.add(new JButton("^ "), BorderLayout.NORTH);
center.add(new JButton("v "), BorderLayout.SOUTH);
center.add(new JButton("O"), BorderLayout.CENTER);
return center;
}
public static void main(String ...args){
new Panels().setVisible(true);
}
public Panels(){
init();
pack();
}
}
注意:我使用JFrame
代替applet。
我刚刚发布了代码,因为它需要很多时间来描述整个程序,我认为只有代码就足够了。
如果您有疑问,请在评论中写下。
答案 1 :(得分:1)
在addCenterPanel
中,您将所有组件直接添加到小程序本身,而不是JPanel
p
。该面板未添加到applet本身。在addInnermostPanel
中,组件再次添加到小程序中,center
JPanel
永远不会添加到容器中