如何使JLabels从下一行开始 [英] How to make JLabels start on the next line
问题描述
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
在每个JLabel从新行开始的地方,如何获得此输出?谢谢
How can I get this output, where each JLabel starts on a new line? Thanks
Economy
Regularity
推荐答案
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.
有很多不同的布局管理器,每个管理器允许您以不同的方式布局控件.默认的布局管理器是FlowLayout
,如您所见,它只是将组件从左到右彼此相邻放置.那是最简单的.其他一些常见的布局管理器是:
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
-将组件排列在具有相等大小的行和列的矩形网格中 -
BorderLayout
-在中央有一个主要组成部分,在上方,下方,左侧和右侧最多具有四个周围的组件. -
GridBagLayout
-所有内置布局管理器中的Big Bertha,它使用起来最灵活但也最复杂.
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.
例如,您可以使用 BoxLayout 布置标签.
You could, for example, use a BoxLayout to layout the labels.
BoxLayout
要么将其组件堆叠在一起,要么将它们放置在一行中-您可以选择.您可能会认为它是FlowLayout
的一个版本,但是功能更强大.这是一个应用程序的图片,它演示了如何使用BoxLayout
来显示组件的居中列:
BoxLayout
either stacks its components on top of each other or places them in a row — your choice. You might think of it as a version ofFlowLayout
, but with greater functionality. Here is a picture of an application that demonstrates usingBoxLayout
to display a centered column of components:
使用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);
...
这篇关于如何使JLabels从下一行开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!