简体   繁体   English

Java GridBagLayout JComponents放置

[英]Java GridBagLayout JComponents placement

I'm trying to place one label and one textfield on one row and on the second row another label and textfield. 我试图在一行上放置一个标签和一个文本字段,在第二行上放置另一个标签和文本字段。 The problem is that the second pair of JComponents go on the first line too. 问题在于第二对JComponent也位于第一行。 I'm using first a GridLayout(2,1) where in the first row I place a JPanel with GridBagLayout with these two pairs and on the second row I use a JPanel with GridBagLayout where I place a submit button. 我首先使用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);

You haven't supplied the GridBagConstraints to the container when adding your components... 添加组件时尚未向GridBagConstraints提供GridBagConstraints

firstPanel.add(name);

Instead, use something more like 相反,使用更像

firstPanel.add(name, c);

This will pass the component and constraints to the GridLayoutManager 这会将组件和约束传递给GridLayoutManager

See How to use GridBagLayout for more details 有关更多详细信息,请参见如何使用GridBagLayout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM