如何使JLabel从下一行开始

JPanel pMeasure = new JPanel(); .... JLabel economy = new JLabel("Economy"); JLabel regularity = new JLabel("Regularity"); pMeasure.add(economy); pMeasure.add(regularity); ... 

当我运行上面的代码时,我得到这个输出:

 Economy Regularity 

如何获得此输出,每个JLabel在新行上启动? 谢谢

 Economy Regularity 

您需要使用布局管理器来控制JPanel控件的定位和大小。 布局管理器负责放置控件,确定它们的位置,它们的大小,它们之间的空间大小,调整窗口大小时会发生什么等等。

有大量不同的布局管理器,每个布局管理器允许您以不同的方式布局控件。 默认的布局管理器是FlowLayout ,正如您所见,它只是将组件从左到右放置在彼此旁边。 那是最简单的。 其他一些常见的布局管理器是:

  • GridLayout – 在具有相等大小的行和列的矩形网格中排列组件
  • BorderLayout – 中心有一个主要组件,上方,下方,左侧和右侧最多有四个周围组件。
  • GridBagLayout – 所有内置布局管理器的Big Bertha,它是最灵活但也最复杂的使用。

例如,您可以使用BoxLayout来布局标签。

BoxLayout要么将其组件堆叠在一起,要么将它们放在一行 – 您的选择。 您可能会将其视为FlowLayout一个版本,但具有更强大的function。 下面是一个应用程序的图片,演示如何使用BoxLayout显示组件的居中列:

BoxLayout截图http://sofzh.miximages.com/java/BoxLayoutDemo.png

使用BoxLayout的代码示例如下:

 JPanel pMeasure = new JPanel(); .... JLabel economy = new JLabel("Economy"); JLabel regularity = new JLabel("Regularity"); pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS)); pMeasure.add(economy); pMeasure.add(regularity); ... 

我读了这段代码:

  pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.VERTICAL)); 

似乎BoxLayout没有VERTICAL。 在搜索时,这将使用以下代码:

  pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS)); 

以下是您需要使用的内容:

 JLabel economy = new JLabel("Economy
Regularity");

一种快速的方法是在JLabel中使用html。 例如,包括标签。

否则,实现BoxLayout。

为每一行创建一个单独的JPanel,并设置尺寸以适合每个单词:

 JLabel wordlabel = new JLabel("Word"); JPanel word1 = new JPanel(); word1.setPreferredSize(new Dimension(#,#); 

这适用于每个单词。 然后,您可以将每个JPanel添加到主JPanel。 这也允许您在每个单词旁边添加其他组件。