gpt4 book ai didi

Java GridBagLayout JComponent 放置

转载 作者:行者123 更新时间:2023-12-01 11:45:01 24 4
gpt4 key购买 nike

我试图将一个标签和一个文本字段放置在一行上,并在第二行上放置另一个标签和文本字段。问题是第二对 JComponent 也位于第一行。我首先使用 GridLayout(2,1),在第一行中,我将带有 GridBagLayout 的 JPanel 与这两对一起放置,在第二行中,我使用带有 GridBagLayout 的 JPanel,在其中放置一个提交按钮。

    JDialog dialog;
JLabel name;
JLabel rating;

dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setSize(300, 350);
//dialog.setResizable(false);
dialog.setLocationRelativeTo(null);


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(2,1));
dialog.getContentPane().add(mainPanel);

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

mainPanel.add(firstPanel);

name = new JLabel("Name:");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
firstPanel.add(name);
JTextField label1 = new JTextField(10);
c.gridx = 1;
c.gridy = 0;
firstPanel.add(label1);

rating = new JLabel("Rating:");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
firstPanel.add(rating);
JTextField label2 = new JTextField(10);
c.gridx = 1;
c.gridy = 1;
firstPanel.add(label2);

JPanel submit = new JPanel();
submit.setLayout(new GridBagLayout());
mainPanel.add(submit);
JButton buton = new JButton("Submit");
submit.add(buton);
dialog.pack();
dialog.setVisible(true);

最佳答案

添加组件时,您尚未向容器提供 GridBagConstraints...

firstPanel.add(name);

相反,使用更像的东西

firstPanel.add(name, c);

这会将组件和约束传递给 GridLayoutManager

参见How to use GridBagLayout了解更多详情

关于Java GridBagLayout JComponent 放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com