我正在设计一个使用GridBagLayout
显示项目的面板。我正在寻找的结果是这样的:
但是,目前我看到以下内容:
然后我初始化我的面板并设置布局:
JPanel surveyDetailsFieldsPane = new JPanel();
surveyDetailsFieldsPane.setMinimumSize(new Dimension(0, 300));
surveyDetailsFieldsPane.setPreferredSize(new Dimension(410, 300));
GridBagLayout detailsGridBagLayout = new GridBagLayout();
surveyDetailsFieldsPane.setLayout(detailsGridBagLayout);
surveyDetailsFieldsPane.setBorder(new EmptyBorder(STANDARD_BORDER,
STANDARD_BORDER,
STANDARD_BORDER,
STANDARD_BORDER));
我初始化我的组件以添加到网格中:
JLabel jobNameLbl.setText("Job Name:");
JTextField jobNameTF = new JTextField(20);
JLabel jobNumLbl.setText("Job Number:");
JTextField jobNumTF = new JTextField(12);
然后我使用addComponentToSurveyDetailsGrid
方法将组件添加到网格中:
// Row 1
addComponentToSurveyDetailsGrid(jobNameLbl, 0, 0, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
addComponentToSurveyDetailsGrid(jobNameTF, 1, 0, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
// Row 2
addComponentToSurveyDetailsGrid(jobNumLbl, 0, 1, 1, 1, 10, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
addComponentToSurveyDetailsGrid(jobNumTF, 1, 1, 0, 1, 40, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
addComponentToSurveyDetailsGrid(dateLbl, 4, 1, 1, 1, 10, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
addComponentToSurveyDetailsGrid(dateTF, 5, 1, 0, 1, 40, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
使用的方法如下所示:
private void addComponentToSurveyDetailsGrid(Component component, int gridX, int gridY,
int gridWidth, int gridHeight, int weightX,
int weightY, int fill, int anchor) {
GridBagConstraints constraint = new GridBagConstraints();
constraint.gridx = gridX;
constraint.gridy = gridY;
constraint.gridwidth = gridWidth;
constraint.gridheight = gridHeight;
constraint.weightx = weightX;
constraint.weighty = weightY;
constraint.fill = fill;
constraint.anchor = anchor;
constraint.insets = new Insets(Dimens.SMALL_BORDER,
Dimens.SMALL_BORDER,
Dimens.SMALL_BORDER,
Dimens.SMALL_BORDER);
detailsGridBagLayout.setConstraints(component, constraint);
surveyDetailsFieldsPane.add(component);
}
请告诉我这里做错了什么!
答案 0 :(得分:3)
我怀疑它会解决你的问题,但是:
addComponentToSurveyDetailsGrid(jobNumLbl, 0, 1, 1, 1, 10, 0, ...
addComponentToSurveyDetailsGrid(jobNumTF, 1, 1, 0, 1, 40, 0, ...
addComponentToSurveyDetailsGrid(dateLbl, 4, 1, 1, 1, 10, 0, ...
addComponentToSurveyDetailsGrid(dateTF, 5, 1, 0, 1, 40, 0, ...
您的gridx值为0,1,4,5。
您不能尝试将组件添加到网格4. GridBagLayout不会奇怪地将组件添加到网格2和3.所以您需要将组件添加到网格2和3。
如果希望jobname文本字段占用其下3个组件的空间,则在添加jobname文本字段时需要指定gridwidth值为3。
阅读How to Use GridBagLayout上的Swing教程中的部分。本教程将解释gridwidth参数的工作原理,并为您提供下载和测试的工作示例。