如何让 JLabels 从下一行开始
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 pMeasure = new JPanel();
....
JLabel economy = new JLabel("Economy");
JLabel regularity = new JLabel("Regularity");
pMeasure.add(economy);
pMeasure.add(regularity);
...
When I run the code above I get this output:
Economy Regularity
How can I get this output, where each JLabel starts on a new line? Thanks
Economy
Regularity
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用布局管理器来控制
JPanel
中控件的位置和大小。布局管理器负责放置控件,确定它们的位置,它们有多大,它们之间有多少空间,调整窗口大小时会发生什么,等等。有很多不同的布局管理器,每个都允许您布局控件以不同的方式。默认布局管理器是 FlowLayout,正如您所见,它只是将组件从左到右相邻放置。这是最简单的。其他一些常见的布局管理器有:
GridLayout
- 将组件排列在行和列大小相同的矩形网格中BorderLayout
- 中心有一个主要组件,周围最多有四个组件上方、下方、左侧和右侧的组件。GridBagLayout
- 所有内置布局管理器中的 Big Bertha,它是最灵活的,但使用起来也是最复杂的。例如,您可以使用 BoxLayout 进行布局标签。
使用
BoxLayout
的代码示例如下:You'll want to play around with layout managers to control the positioning and sizing of the controls in your
JPanel
. Layout managers are responsible for placing controls, determining where they go, how big they are, how much space is between them, what happens when you resize the window, etc.There are oodles of different layout managers each of which allows you to layout controls in different ways. The default layout manager is
FlowLayout
, which as you've seen simply places components next to each other left to right. That's the simplest. Some other common layout managers are:GridLayout
- arranges components in a rectangular grid with equal-size rows and columnsBorderLayout
- has one main component in the center and up to four surrounding components above, below, to the left, and to the right.GridBagLayout
- the Big Bertha of all the built-in layout managers, it is the most flexible but also the most complicated to use.You could, for example, use a BoxLayout to layout the labels.
An example of code using
BoxLayout
would be:我读了这段代码:
看来BoxLayout没有VERTICAL。搜索后,这将使用以下代码工作:
I read this piece of code:
It seems BoxLayout doesn't have VERTICAL. Upon searching, this will work using the following code:
这是您需要使用的:
Here is what you need to use:
一种快速方法是在 JLabel 中使用 html。
例如,包含
标签。否则,实现 BoxLayout。
A quick way is to use html within the JLabel.
For instance include the
<br/>
tag.Otherwise, implement a BoxLayout.
为每一行创建一个单独的 JPanel,并设置适合每个单词的尺寸:
这应该适用于每个单词。然后,您可以将每个 JPanel 添加到您的主 JPanel 中。这还允许您在每个单词旁边添加其他组件。
Make a separate JPanel for each line, and set the dimensions to fit each word:
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.