12
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
4

5 回答 5

23

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

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

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

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

BoxLayout要么将其组件堆叠在一起,要么将它们排成一排——你的选择。您可能会将其视为 的一个版本FlowLayout,但具有更强大的功能。这是一个应用程序的图片,演示了如何使用BoxLayout来显示一个居中的组件列:

BoxLayout 截图

使用代码的示例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);
...
于 2009-10-08T00:14:21.743 回答
5

我读了这段代码:

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

BoxLayout 似乎没有 VERTICAL。搜索后,这将使用以下代码工作:

 pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS));
于 2013-03-31T00:02:30.533 回答
3

这是您需要使用的:

JLabel economy = new JLabel("<html>Economy<br>Regularity</html>");
于 2011-08-16T21:23:06.093 回答
0

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

否则,实现 BoxLayout。

于 2009-10-08T00:20:52.557 回答
0

Make a separate JPanel for each line, and set the dimensions to fit each word:

JLabel wordlabel = new JLabel("Word");

JPanel word1 = new JPanel();
word1.setPreferredSize(new Dimension(#,#);

This should work for each word. You can then add each of those JPanels to your main JPanel. This also allows you to add other components next to each word.

于 2014-01-20T16:15:30.237 回答