尽管没有布局管理器也是可以的,但您应该尽可能使用布局管理器。布局管理器使调整与外观依赖的组件外观,不同的字体大小,容器的不断变化的大小以及不同的语言环境变得更加容易。布局管理器也可以很容易地被其他容器和其他程序重用。
注意: 本课程涵盖手工编写布局代码,这可能会很困难。如果您不希望学习布局管理的所有详细信息,则可能更喜欢将
GroupLayout
布局管理器与构建器工具结合使用来布局GUI。NetBeans IDE就是这样一种构建器工具 。否则,如果您想手工编写代码并且不想使用GroupLayout
,那么GridBagLayout
建议将其作为下一个最灵活,功能最强大的布局管理器。
如果您对使用JavaFX创建GUI感兴趣,请参阅使用JavaFX中的 布局。
如果容器中容纳的组件的大小不受容器的大小或字体,外观和语言的变化的影响,则绝对定位可能很有意义。包含内部框架的桌面窗格 在此类别中。内部框架的大小和位置不直接取决于桌面窗格的大小。程序员确定桌面窗格中内部框架的初始大小和位置,然后用户可以移动或调整框架的大小。在这种情况下,不需要布局管理器。
绝对定位可能有意义的另一种情况是定制容器的情况,该容器执行特定于容器的尺寸和位置计算,并且可能需要了解容器的特殊状态。分割窗格就是这种情况 。
创建没有布局管理器的容器涉及以下步骤。
- 通过调用将容器的布局管理器设置为null
setLayout(null)
。 - 为容器的每个子代调用
Component
类的setbounds
方法。 - 调用
Component
类的repaint
方法。
但是,如果调整包含容器的窗口的大小,则使用绝对定位的容器创建容器会引起问题。
这是其内容窗格使用绝对定位的框架的快照。
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class AbsoluteLayoutDemo {
public static void addComponentsToPane(Container pane) {
pane.setLayout(null);
JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");
pane.add(b1);
pane.add(b2);
pane.add(b3);
Insets insets = pane.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top, size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top, size.width + 50, size.height + 20);
}
/**
* Create the GUI and show it. For thread safety, this method should be invoked
* from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("AbsoluteLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
// Size and display the window.
Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right, 125 + insets.top + insets.bottom);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}