[英]GridBagLayout not aligning jlabel and jbutton
因此,我使用了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);
}
}
我相信您的“问题”来自锚参数的错误使用。
从https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html中 :
锚点:当组件小于其显示区域时使用,以确定放置组件的位置(在区域内)。 有效值(定义为GridBagConstraints常数)为CENTER(默认值),PAGE_START,PAGE_END,LINE_START,LINE_END,FIRST_LINE_START,FIRST_LINE_END,LAST_LINE_END和LAST_LINE_START。
因此,anchor用于指定组件在其单元格中的位置。
这里有两个单元格:
如您所见,单元格在同一行上。 如果要将按钮放在标签下方,请使用gridx / gridy约束:
gridx,gridy在组件的左上方指定行和列。 最左列的地址为gridx = 0,最上一行的地址为gridy = 0。 使用GridBagConstraints.RELATIVE(默认值)可以指定将组件放置在刚添加容器之前已添加到容器中的组件的右侧(对于Gridx)或恰好位于其下方(对于Gridy)。 我们建议为每个组件指定gridx和gridy值,而不仅仅是使用GridBagConstraints.RELATIVE; 这往往会导致更可预测的布局。
尝试:
gbc.gridy = 1;
gbc2.gridy = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.