使用空布局的 JFrame 非常小
我正在编写一个简单的程序来显示一个框架.但是,当我键入 setLayout(null); 时,框架变得非常小;但是如果我忽略这个命令,按钮总是在顶部中心有人能指出我的错误吗?
Hi I am writing a simple program to display a frame. However the frame turns out real small when I type setLayout(null); But if i ignore this command, the button is always at the top center Can some one point out my error?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class theframe {
private static void create() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insets insets = frame.getInsets();
frame.setSize(500 + insets.left + insets.right, 350 + insets.top + insets.bottom);
add(frame.getContentPane()); //my function add
frame.pack();
frame.setVisible(true);
}
public static void add(Container pane) {
pane.setLayout(null);
Insets insets = pane.getInsets();
JPanel p1 = new JPanel();
p1.setPreferredSize(new Dimension(500, 350));
JButton b1 = new JButton("one");
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);
pane.add(p1);
p1.add(b1);
}
public static void main(String Args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
create();
}
});
}
}
推荐答案
你正在调用具有绝对定位(null 布局)的 pack()
方法,你应该使用LayoutManager 而不是使用将布局设置为 null
.
You're calling pack()
method with absolute positioning (null layout), you should use LayoutManager instead of using setting the layout to null
.
只需删除这一行:
pane.setLayout(null);
注意:听从我的建议,自学LayoutManagers
,因为如果你拒绝学习,你可能会去null
布局,是的,它更容易,但强烈建议不要使用它.
NOTE: take my advice and learn yourself LayoutManagers
, because if you refuse to learn, you'll probably go to null
layout, yes,it is easier but highly recommended to not use it.
你必须知道的一些基本知识:
Some basic things you must know:
JFrame
的默认布局是 BorderLayout,只有五个位置可以放置组件,如链接所示.- FlowLayout 是每个默认布局管理器面板.它只是将组件布置在一行中,如果其容器不够宽,则开始一个新行.
- The default layout of
JFrame
is BorderLayout, which there only five locations you can put your components in as shown in the link. - FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide.
毕竟,在开始使用之前,请阅读有关 LayoutManagers 的更多信息swing,相信我,它让你的工作变得更轻松,试试吧,太棒了.
After all, read more about LayoutManagers before starting using swing, belive me it makes your work very easier, just try it, it's amazing.
相关文章