【问题标题】:How can I align my Jframe labels and buttons如何对齐我的 Jframe 标签和按钮
【发布时间】:2013-03-13 14:56:44
【问题描述】:

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

}

【问题讨论】:

    标签: java swing jframe layout-manager springlayout


    【解决方案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,因为该方法不会知道按钮。

    【讨论】:

      【解决方案2】:

      可以试试这个方法吗?

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

      【讨论】:

      • 这不起作用。我不知道为什么。不过,另一个答案确实如此。感谢您的努力:)
      猜你喜欢
      • 2015-01-25
      • 2021-03-09
      • 2016-02-03
      • 2017-01-10
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      相关资源
      最近更新 更多