java - Java for 循环逻辑的问题

标签 java for-loop

我无法理解为什么我的 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 is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false.

所以您的起点是 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/

相关文章:

java - 保留对 Actor 系统的引用

java - 将原始文本添加到 SOAP header

java - 在数组中使用循环和随机字符java

python - 简单的 Python 生成器跳过 for 循环的步骤

c# - 仅当在循环的所有迭代中都满足条件时才执行操作

java - 禁止在 Linux 和 Windows 中运行程序

java - 在 Android 上分析来自麦克风的声音(谐波、分音、泛音)

java - 处理 wicket 中 AutoCompleteTextField 的 onchange 事件

r - R 中 for 循环的语法

javascript - 为什么 javascript 数组会被键值填充