Java GridBagLayout JComponent 放置

标签 java swing

我试图将一个标签和一个文本字段放置在一行上,并在第二行上放置另一个标签和文本字段。问题是第二对 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/

相关文章:

java - 如何从另一个类访问具有多个 swing 组件的方法? ( java )

java - JDialog 中的 JButton 保持按下状态

java - Android ListView 对象不喜欢 new onItemClickListener() 作为 setOnitemClickListener() 的参数

java - 使用maven的spring hibernate集成中的org.springframework.beans.factory.BeanCreationException

java - 更改数据后刷新 JTable

java - JEdi​​torPane 在显示特定的非动画 GIF 时 CPU 使用率较高

java - 以编程方式使用硬件随机数生成器

java - 如何将 bean 注入(inject) @Controller 类

java - 动态代理 : how to handle nested method calls

Java textBox.setText() 错误(文本太多?)