简体   繁体   English

将布局管理器添加到JPanel和JFrame

[英]Adding Layout Manager to JPanel and JFrame

I am trying to add buttons to a Frame which I am trying in two ways. 我正在尝试向框架添加按钮,这有两种方法。

  1. Changing the Layout of JPanel and then adding buttons directly to the panel. 更改JPanel的布局,然后将按钮直接添加到面板。 (Commented section in below code). (下面的代码中的注释部分)。 Then I am adding the panel to a frame. 然后,我将面板添加到框架中。 This approach worked and it shows buttons in a JFrame . 这种方法有效,并且在JFrame显示按钮。

  2. Creating a BorderLayout , adding buttons using addLayoutComponents() method. 创建一个BorderLayout ,使用addLayoutComponents()方法添加按钮。 Then adding this bl ( BorderLayout reference) to the panel and then JFrame. 然后将此blBorderLayout参考)添加到面板中,然后添加JFrame。 Why is this approach not showing buttons in the frame? 为什么这种方法没有在框架中显示按钮? Where did I go wrong? 我哪里做错了?

Can anyone help me in learning AWT components? 谁能帮助我学习AWT组件? I mean what to read first and sequence of concepts . 我的意思是首先阅读什么和概念序列。

jf = new JFrame();
jp= new JPanel(new BorderLayout());

 /*jp.add(new JButton("North"), BorderLayout.NORTH);
 jp.add(new JButton("South"), BorderLayout.SOUTH);
 jp.add(new JButton("East"), BorderLayout.EAST);
 jp.add(new JButton("West"), BorderLayout.WEST);
 jp.add(new JButton("Center"), BorderLayout.CENTER);
 jf.add(jp);
 */

 BorderLayout bl = new BorderLayout();

 bl.addLayoutComponent(new JButton("North"), BorderLayout.NORTH);
 bl.addLayoutComponent(new JButton("South"), BorderLayout.SOUTH);
 bl.addLayoutComponent(new JButton("East"), BorderLayout.EAST);
 bl.addLayoutComponent(new JButton("West"), BorderLayout.WEST);
 bl.addLayoutComponent(new JButton("Center"), BorderLayout.CENTER);
 jp.setLayout(bl);
 jf.add(jp);

The second way is not working because it's wrong. 第二种方法不起作用,因为它是错误的。 You shouldn't be adding components directly to the layout manager but rather to the container that uses the layout manager as is well outlined in the layout manager tutorial here: Layout Manager Tutorial . 您不应该将组件直接添加到布局管理器中,而应该添加到使用布局管理器的容器中,如此处的布局管理器教程中概述的那样: 布局管理器教程 Per the BorderLayout API, you the coder shouldn't directly call the addLayoutComponent method, but rather it is called indirectly by the container itself when components are added to the container. 根据BorderLayout API,编码人员不应直接调用addLayoutComponent方法,而应在将组件添加到容器时由容器本身间接调用。 The method adds the component to the layout but not to the container itself , and that's a key difference. 该方法将组件添加到布局中, 但不添加到容器本身 ,这是一个关键的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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