简体   繁体   English

我可以简化这个for循环吗?

[英]Can I simplify this for loop?

The following segment of code is from a system that generates a 5 by 5 grid of JButtons. 以下代码段来自于生成5 x 5网格的JButton的系统。 I need to iterate over an ArrayList of JButtons and pass the row and column of the JButton into the ButtonListener 's constructor. 我需要遍历一个ArrayListJButtons与行和列通过JButtonButtonListener的构造。 The way the code is currently shown below works, but I was wondering if I could clean up the code at all or re-factor in any way. 当前在下面显示代码的方式有效,但是我想知道是否可以清理代码或以任何方式重构。 I seem to have a lot of instructions for trying to construct a grid. 我似乎有很多有关尝试构建网格的说明。

    int row = 1, col = 1;
    for (JButton curButton : view.getButtons()) {

        curButton.addActionListener(new ButtonListener(row, col));
        row++;

        if (row > 5) {
            row = 1;
            col++;
        }           
    }

Is there any way I can improve the quality or simplify the above code segment? 有什么办法可以提高质量或简化上面的代码段?

int iterator = 0;
for (JButton curButton : view.getButtons()) {

    curButton.addActionListener(new ButtonListener(iterator%5 + 1, iterator/5 + 1));

    iterator++; 
}

Note here that I'm using integer division, which always rounds down. 注意这里我使用整数除法,该除法总是四舍五入。 iterator/5 + 1 will map {0,1,2,3,4,5,6,...} to {1,1,1,1,1,2,2...} iterator/5 + 1将映射{0,1,2,3,4,5,6,...}到{1,1,1,1,1,2,2 ...}

Can't you have: 你不能有:

col = row = 5;
for (int i = 0; i < col; i++) {
    for (int j = 0; j < row; j++) {
         curButton.addActionListener(new ButtonListener(i, j));
    }
}

Might have to make col and row 6 or make i and j start at a different number. 可能必须使col和row 6或使i和j从另一个数字开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM