Java GridBagLayout JComponents放置

时间:2015-03-23 20:32:28

标签: java swing

我正在尝试在一行上放置一个标签和一个文本字段,在第二行放置另一个标签和文本字段。问题是第二对JComponents也在第一行。我首先使用的是一个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);

1 个答案:

答案 0 :(得分:1)

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

firstPanel.add(name);

相反,请使用更像

的内容
firstPanel.add(name, c);

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

有关详细信息,请参阅How to use GridBagLayout