Swing GridBagLayout - 对齐问题

时间:2015-04-09 21:00:32

标签: java swing alignment layout-manager gridbaglayout

我有一个带有JLabel,JTextField的JPanel和另一个带有JLabel的JPanel。

    createDomainPanel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    //createDomainPanel.setSize(600, 300);
    gbc.fill=GridBagConstraints.HORIZONTAL;


    gbc.gridx=0;
    gbc.gridy=0;
    createDomainPanel.add(new JLabel("Enter the name of the domain"), gbc);

    gbc.gridx=0;
    gbc.gridy=1;        
    createDomainPanel.add(domainName, gbc);

    JPanel result = new JPanel(new FlowLayout());
    result.add(successMessage);
    gbc.anchor=GridBagConstraints.LAST_LINE_START;
    gbc.gridx=0;
    gbc.gridy=2;
    createDomainPanel.add(result);

最后一个JLabel结果在某个操作后打印成功消息。

 public void actionPerformed(ActionEvent e) {
        SimpleDbConnect dbc = new SimpleDbConnect();
        String name = "";
        if (e.getSource()==domainName){
            name=e.getActionCommand();
            boolean success = dbc.addDomain(name);
            if (success){
                successMessage.setText("Domain "+ name + " added successfully");
            }
        }

    }   

然而问题是当我获得成功响应时,成功消息而不是位于底部会出现在第一个JLabel的右侧。 我对Swings很新。任何人都可以帮助我吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

添加result面板时忘记传递约束

createDomainPanel.add(result, gbc);