【问题标题】:How to make JLabels start on the next line如何让 JLabels 在下一行开始
【发布时间】:2010-12-04 19:52:22
【问题描述】:
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

【问题讨论】:

标签: java swing jpanel jlabel layout-manager


【解决方案1】:

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

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

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

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

BoxLayout 要么将其组件堆叠在一起,要么将它们排成一排——你的选择。您可能会认为它是FlowLayout 的一个版本,但功能更强大。这是一个应用程序的图片,它演示了使用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);
...

【讨论】:

    【解决方案2】:

    我看了这段代码:

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

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

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

    【讨论】:

    • @pricepiero 谢谢pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS)); 为我解决了这个问题。将 JPanel 中的所有组件垂直布局。
    【解决方案3】:

    这是你需要使用的:

    JLabel economy = new JLabel("<html>Economy<br>Regularity</html>");
    

    【讨论】:

    • 这将让您只创建一个 JLabel,如果您正在等待数据进入它需要您有更多的代码。这……效率低下。
    【解决方案4】:

    一种快速的方法是在 JLabel 中使用 html。 例如包含&lt;br/&gt; 标签。

    否则,实现 BoxLayout。

    【讨论】:

      【解决方案5】:

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

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

      这应该适用于每个单词。然后,您可以将这些 JPanel 中的每一个添加到您的主 JPanel。这还允许您在每个单词旁边添加其他组件。

      【讨论】:

        猜你喜欢
        • 2018-09-25
        • 2014-09-21
        • 2018-03-26
        • 2019-08-29
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        • 1970-01-01
        • 2021-06-18
        相关资源
        最近更新 更多