gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:30:56 25 4
gpt4 key购买 nike

我想在窗口的中央放置两个标签。我让它使用 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/

25 4 0