0

我正在尝试编辑我发现的一段示例代码来创建表单。示例代码包括完美对齐的 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();
        }
    });
}

}

4

2 回答 2

1

问题的发生是因为该方法将标签及其文本字段makeCompactGrid压缩到所需的大小,并且您没有对按钮施加任何约束以让布局知道将其放置在哪里。JPanel

您可以创建一个空标签并将其添加到您的按钮之后,然后调用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因为该方法不会知道按钮。

于 2013-03-13T15:39:35.470 回答
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);
于 2013-03-13T15:02:21.350 回答