我无法理解为什么我的for循环没有按照我的意愿行事.我的循环的目的是将多个文本字段添加到GUI,准确地说是70.7横穿,10横.它添加了很好的字段,但是停止了比我想要的更短的一行和一列.这似乎足以确定问题的信息,但我不能,所以我来到这里.
for(int i = 0; i < 6; i++){
for(int j = 0; j < 9; j++){
OT2Field[i][j] = new JTextField();
OT1Field[i][j] = new JTextField();
STField[i][j] = new JTextField();
}
}
int xPointer = 3;
int yPointer = 7;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 9; j++){
addTimeFieldBorder0010(option3, OT2Field[i][j], gridbag, gbc, xPointer, yPointer, 1, 1, 0);
yPointer = yPointer + 3;
}
xPointer++;
yPointer = 7;
}
}
private void addTimeFieldBorder0010(JComponent container, JComponent component,
GridBagLayout gridbag, GridBagConstraints gbc,
int x, int y, int height, int width, double weightx) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = height;
gbc.gridwidth = width;
gbc.weightx = weightx;
((JTextField) component).setHorizontalAlignment(JLabel.CENTER);
component.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.red));
component.setFont(component.getFont().deriveFont(18.0f));
component.setForeground(Color.red);
component.setBackground(Color.YELLOW);
gridbag.setConstraints(component, gbc);
container.add(component, gbc);
}
Run Code Online (Sandbox Code Playgroud)
- 如果左侧操作数的值小于右侧操作数的值,则
<
运算符产生true
的值为,否则为false
.
所以,你开始i = 0
和循环,同时i
是少比6.您需要循环,当它小于7,或小于或等于6.这同样适用于你的下一个循环.
将您的两个循环更改为:
for(int i = 0; i < 7; i++){
for(int j = 0; j < 10; j++){
//stuff
}
}
Run Code Online (Sandbox Code Playgroud)
外部循环仅从0到5执行,内部循环仅从0到8执行.将循环更改为
for(int i = 0; i < 7; i++){
for(int j = 0; j < 10; j++){
OT2Field[i][j] = new JTextField();
OT1Field[i][j] = new JTextField();
STField[i][j] = new JTextField();
}
}
Run Code Online (Sandbox Code Playgroud)
该<
符号返回false时,左边的值等于正确.因此i=6
,i<6
返回false,因此您缺少一次迭代.
你在0 to 5
for循环i
和0 to 8
for 循环之间循环j
.这就是它停止一行一列的原因.你应该改变它们如下:
for(int i = 0; i <= 6; i++){
for(int j = 0; j <= 9; j++){
...
}
}
Run Code Online (Sandbox Code Playgroud)
要么
for(int i = 0; i < 7; i++){
for(int j = 0; j < 10; j++){
...
}
}
Run Code Online (Sandbox Code Playgroud)