解决常见布局问题

原文: https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html


Note: This lesson covers writing layout code by hand, which can be challenging. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. One such builder tool is the NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager.


如果您对使用 JavaFX 创建 GUI 感兴趣,请参阅在 JavaFX 中使用布局。

问题:如何指定组件的确切大小?

  • 少数更现代的布局管理器提供了覆盖组件设置大小的方法。检查您使用的布局管理器是否允许您指定组件大小。
  • 确保您确实需要设置组件的确切大小。每个 Swing 组件都有不同的首选大小,具体取决于它使用的字体和外观。因此,指定 Swing 组件的确切大小通常没有意义。
  • 如果组件不受布局管理器控制,则可以通过调用其上的setSizesetBounds方法来设置其大小。否则,您需要提供大小提示,然后确保使用的布局管理器遵循大小提示。
  • 如果扩展 Swing 组件类,则可以通过覆盖组件的getMinimumSizegetPreferredSizegetMaximumSize方法来提供大小提示。这个方法有什么好处,每个得到 _Xxxx_ 大小方法可以通过调用super.get _Xxxx_ Size()来获取组件的默认大小提示。然后,如果需要,它可以在返回之前调整大小。这对于文本组件尤其方便,您可能需要修改宽度,但要根据内容确定高度。但是,有时在GridBagLayout和文本字段中会遇到问题,其中如果容器的大小小于首选大小,则使用最小大小,这会导致文本字段显着缩小。
  • 给出大小提示的另一种方法是调用组件的setMinimumSizesetPreferredSizesetMaximumSize方法。
  • 如果为已经可见的组件指定新的大小提示,则需要在其上调用revalidate方法,以确保再次布置其包含层次结构。然后调用repaint方法。

Note: No matter how you specify your component’s size, be sure that your component’s container uses a layout manager that respects the requested size of the component. The FlowLayout and GridBagLayout managers use the component’s preferred size (the latter depending on the constraints that you set), but BorderLayout and GridLayout usually do not. The BoxLayout manager generally uses a component’s preferred size (although components can be larger), and is one of the few layout managers that respects the component’s maximum size.


问题:我将组件添加到容器后没有出现。

  • 在添加组件之前,需要先调用revalidaterepaint,然后才能显示在容器中。

问题:我的自定义组件尺寸太小。

  • 组件是否实现getPreferredSizegetMinimumSize方法?如果是这样,他们会返回正确的值吗?
  • 您使用的布局管理器是否可以使用尽可能多的空间?有关选择布局管理器并指定它使用特定组件的最大可用空间的一些提示,请参阅选择布局管理器的提示。

如果在此列表中没有看到问题,请参阅解决常见组件问题