我无法理解为什么我的 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);
}
最佳答案
根据Java Language Specification §15.20.1 ,
- The value produced by the
<
operator istrue
if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise isfalse
.
所以您的起点是 i = 0
并循环 i
小于 6。当它小于 7 或小于或等于 6 时,您需要循环。这同样适用于您的下一个循环。
将您的两个循环更改为:
for(int i = 0; i < 7; i++){
for(int j = 0; j < 10; j++){
//stuff
}
}
关于java - Java for 循环逻辑的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22302922/