繁体   English   中英

如何对齐Jframe标签和按钮

[英]How can I align my Jframe labels and buttons

我正在尝试编辑创建表单的示例代码。 该示例代码包括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();
        }
    });
}

}

发生问题是因为方法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 ,这可能无法很好地工作,因为该方法将不知道按钮。

可以尝试这种方法吗?

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);

暂无
暂无

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

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