java - 两个标签位于中心的中间

标签 java swing user-interface awt

我想在窗口的中央放置两个标签。我让它使用 1 个标签和以下代码:

截图:http://abload.de/img/scr1g6u0f.png

public static void main(String[] args)
{
    JFrame contentPane = new JFrame();
    contentPane.setBounds(100, 100, 450, 300);
    JPanel centerPanel = new JPanel(new BorderLayout()); 

    JLabel label = new JLabel("center1");
    centerPanel.add(label, BorderLayout.CENTER); 

    contentPane.add(centerPanel, BorderLayout.CENTER);
    contentPane.setVisible(true);
}

现在我想要第一个标签旁边的另一个标签。我尝试使用 flowlabel,但它们被放置在 BorderLayout.CENTER 的顶部

截图:http://abload.de/img/scr2a3u26.png

public static void main(String[] args)
{
    JFrame contentPane = new JFrame();
    contentPane.setBounds(100, 100, 450, 300);
    JPanel centerPanel = new JPanel(new BorderLayout()); 

    JLabel label1 = new JLabel("center1");
    JLabel label2 = new JLabel("center2");

    JPanel flowPanel = new JPanel(new FlowLayout());
    flowPanel.add(label1);
    flowPanel.add(label2);

    centerPanel.add(flowPanel, BorderLayout.CENTER); 

    contentPane.add(centerPanel, BorderLayout.CENTER);
    contentPane.setVisible(true);
}

谢谢!

最佳答案

使用无约束的 GridBagLayout:

   JPanel centerPanel = new JPanel(new GridBagLayout()); 

   JLabel label1 = new JLabel("center1");
   JLabel label2 = new JLabel("center2");

   JPanel flowPanel = new JPanel(new FlowLayout());
   flowPanel.add(label1);
   flowPanel.add(label2);

   centerPanel.add(flowPanel); 

关于java - 两个标签位于中心的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066047/

相关文章:

java - 我想找到有很多单元测试用例的Java开源项目

线程 "main"java.lang.NullPointerException 七人骰子游戏中的 JAVA 异常

java - 如何更改 JComboBox 和 JButton 的默认输入

java - 将 Jbutton 添加到 Jtable 的每一行

java - 从不同的方法访问 GUI 对象

java - 强制 JOptionPane 保持打开状态

android - GUI 不显示所有收到的数据包

java - 使用帮助参数时覆盖 required() 参数

java - Swing 中带有自定义绘画的分层面板

java - Java Swing 项目中的 Google 音译 API