Java 为什么不';使用LayoutManager时,这些小部件是否出现在我的框架中?
我想利用Java 为什么不';使用LayoutManager时,这些小部件是否出现在我的框架中?,java,swing,Java,Swing,我想利用JFrame的容器的默认布局:一个LayoutManager,避免将其专门化为FlowLayout 所以我写了这段代码: LayoutManager layout_manager = this.getContentPane().getLayout(); layout_manager.addLayoutComponent(null, text_field_add_items); (注意:此指向一个JFrame对象,text\u field\u add\u items是一个TextFiel
JFrame
的容器的默认布局:一个LayoutManager
,避免将其专门化为FlowLayout
所以我写了这段代码:
LayoutManager layout_manager = this.getContentPane().getLayout();
layout_manager.addLayoutComponent(null, text_field_add_items);
(注意:此
指向一个JFrame
对象,text\u field\u add\u items
是一个TextField
,由于setSize
,我为其指定了一个大小)
但什么也没有出现
⑨:我真的想使用LayoutManager
,因为它允许我使用默认布局以外的其他布局(即FlowLayout
),如果我将来需要它的话。
你知道为什么吗
整个来源:
package tp4.bundle_clients;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.LayoutManager;
import javax.swing.WindowConstants;
public class Gui extends JFrame {
public Gui() {
this.setTitle("Client's graphical interface");
this.setSize(500, 250);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.addWidgets();
this.setVisible(true);
}
private void addWidgets() {
JTextField text_field_add_items = new JTextField();
text_field_add_items.setSize(100, 100);
JButton button_add_items = new JButton("Add items");
button_add_items.setSize(100, 100);
JTextField text_field_remove_items = new JTextField();
JButton button_remove_items = new JButton("Remove items");
JButton button_display_storage = new JButton("Display storage");
LayoutManager layout_manager = this.getContentPane().getLayout();
layout_manager.addLayoutComponent(null, text_field_add_items);
layout_manager.addLayoutComponent(null, button_add_items);
}
}
在forFlowLayout
中,对addLayoutComponent
的描述如下:
将指定的零部件添加到布局中此类未使用。
如果LayoutManager
不同,您的代码可能会正常工作,但是使用FlowLayout
,什么也不会发生
不幸的是,您确实需要使用您心目中使用的特定LayoutManager
进行编码;根据LayoutManager
,您可能需要使用add
、addLayoutComponent
,或者完全使用其他功能。这就是说,将布局代码委托给单独的方法或类可能是一个好主意,这样就可以轻松地更改LayoutManager
,而不会破坏代码
编辑:正如camickr所指出的,默认的LayoutManager
是BorderLayout
。对于边框布局,在使用addLayoutComponent
时需要使用约束;看
我真的想使用LayoutManager,因为它允许我使用默认布局以外的其他布局(即FlowLayout)
JFrame内容窗格的默认布局管理器是BorderLayout
而不是FlowLayout
使用LayoutManager
没有意义,因为您需要知道面板的布局管理器是什么,以便正确使用布局管理器。也就是说,许多布局管理器在将构件添加到配电盘时需要使用“约束”
只有像FlowLayout、GridLayout和BoxLayout这样的简单布局管理器允许您添加组件而不受约束
因此,我的建议是不要尝试使用LayoutManager或addLayoutComponent(…)
方法。只需在需要时使用适当的约束将组件添加到面板中。它将使代码更易于理解和维护。您不应该直接调用LayoutManager
方法。容器使用它们来布局其子类
应按以下方式添加组件:
this.getContentPane().add(text_field_add_items);
如果您将来需要使用其他布局,只需更改它即可
this.setLayout(newLayout);
你能发布你做这件事的整个方法吗,包括创建JFrame
?我编辑了我的帖子!好的,您的布局实际上是一个边界布局
,这是默认设置。请参阅对我的答案的编辑,以了解其不起作用的原因。