如何对齐Jframe标签和按钮

时间:2013-03-13 14:56:44

标签: java swing jframe layout-manager springlayout

我正在尝试编辑一些我发现用于创建表单的示例代码。示例代码包括4个完全对齐的标签和文本字段。我试图在最后添加一个按钮,但是按钮与屏幕左上角的标签重叠。我该如何解决这个问题?

public class SpringDemo {
private static void createAndShowGUI() {
    String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
    int labelsLength = labels.length;

    //Create and populate the panel.
    JPanel p = new JPanel(new SpringLayout());
    for (int i = 0; i < labelsLength; i++) {
        JLabel l = new JLabel(labels[i], JLabel.TRAILING);
        p.add(l);
        JTextField textField = new JTextField(10);
        l.setLabelFor(textField);
        p.add(textField);
    }
    JButton l = new JButton("Submit");
    p.add(l);

    //Lay out the panel.
    SpringUtilities.makeCompactGrid(p,
                                    labelsLength, 2, //rows, cols
                                    7, 7,        //initX, initY
                                    7, 7);       //xPad, yPad

    //Create and set up the window.
    JFrame frame = new JFrame("SpringForm");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    p.setOpaque(true);  //content panes must be opaque
    frame.setContentPane(p);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

2 个答案:

答案 0 :(得分:1)

问题出现是因为方法makeCompactGridJPanel压缩到标签及其文本字段所需的大小,并且您没有对按钮施加任何约束以让布局知道在哪里把它。

您可以创建一个空标签并在按钮后添加,然后调用makeCompactGrid,这会将按钮置于最后一个标签下。

喜欢这个

JButton l = new JButton("Submit");
p.add(l);
p.add(new JLabel());
SpringUtilities.makeCompactGrid(p,
                                labelsLength + 1, 2, //rows, cols
                                7, 7,        //initX, initY
                                7, 7);       //xPad, yPad

您还可以尝试在按钮上设置约束以强制布局将其放在您想要的位置,但这可能与makeCompactGrid无法正常工作,因为该方法无法了解按钮。

答案 1 :(得分:0)

可以尝试这种方法吗?

private void addComponent(Container container, Component c, int x, int y,int width, int    
height){ 

c.setBounds(x, y, width, height);
container.add(c);
}

并称之为:

addComponent(container such as JPanel, component such as a JButton, x position, yposition,    
 width, height);