在中心中间的两个标签

时间:2015-03-15 20:52:34

标签: 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);
}

谢谢!

1 个答案:

答案 0 :(得分:2)

使用没有约束的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);