首页 文章

GridBagLayout没有对齐jlabel和jbutton

提问于
浏览
0

所以我正在使用GridBagLayout,我正在尝试在JPanel的中心创建一个JButton,然后在JPanel的顶部有一个JLabel . 当我尝试这样做时,按钮和标签没有对齐 .

码:

package view;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class StartPanel extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    //Declare our global variables
    JButton btnUploadProject;
    JLabel heading;
    GridBagConstraints gbc;
    GridBagConstraints gbc2;
    /**
     * Create the panel.
     */
    public StartPanel() {
        //Set up Panel
        this.setVisible(true);
        setLayout(new GridBagLayout());

        //Create the components
        btnUploadProject = new JButton("Upload A Project");
        heading = new JLabel("Heading test");
        gbc = new GridBagConstraints();
        gbc2 = new GridBagConstraints();

        //Modify components
        btnUploadProject.setPreferredSize(new Dimension(400,100));
        btnUploadProject.setFont(new Font("Arial", Font.PLAIN, 40));
        heading.setFont(new Font("Arial", Font.PLAIN, 40));
        gbc.anchor = GridBagConstraints.CENTER;
        gbc2.anchor = GridBagConstraints.NORTH;
        gbc2.weighty = 1.0;
        //Add the buttons
        this.add(btnUploadProject, gbc);
        this.add(heading, gbc2);
    }

}

对齐错误的图像:
Image of the incorrect alignment:

1 回答

  • 0

    我相信你的“问题”来自错误使用锚参数 .

    来自https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

    anchor:当组件小于其显示区域时使用,以确定放置组件的位置(在区域内) . 有效值(定义为GridBagConstraints常量)是CENTER(默认值),PAGE_START,PAGE_END,LINE_START,LINE_END,FIRST_LINE_START,FIRST_LINE_END,LAST_LINE_END和LAST_LINE_START .

    因此,锚用于指定组件在其单元格中的位置 .

    这里有两个单元格:

    • 第一个(x:0,y:0):包含你的按钮,锚点= CENTER,你的按钮显示在单元格的中心

    • 第二个(x:1,y:0):包含带锚= NORTH的标签,您的标签显示在单元格的北部

    如您所见,单元格位于同一行 . 如果要将按钮放在标签下方,请使用gridx / gridy约束:

    gridx,gridy指定组件左上角的行和列 . 最左边的列的地址为gridx = 0,顶行的地址为gridy = 0 . 使用GridBagConstraints.RELATIVE(默认值)指定组件放置在(对于gridx)的右侧或刚好在下面(对于gridy)放置在添加此组件之前添加到容器的组件 . 我们建议为每个组件指定gridx和gridy值,而不是仅使用GridBagConstraints.RELATIVE;这往往会产生更可预测的布局 .

    尝试:

    gbc.gridy = 1;
    gbc2.gridy = 0;
    

相关问题