Nicz Nicz -4 years ago 48
Java Question

2D Array flip vertically and horizontally

I have this method that's able to rotate the array by 90 degrees. I want to be to flip vertically and horizontally (I'm binding them with different buttons). Here's the method.

private void Rotate90() {
String[][] temp = new String[totalX][totalY];
for (int y = 0; y < totalY; y++) {
for (int x = 0; x < totalX; x++) {
temp[x][y] = fields[x][y].getText();
}
}
for (int y = 0; y < totalY; y++) {
for (int x = 0; x < totalX; x++) {
fields[x][y].setText(temp[y][x]);
}
}
Draw();
}

Answer Source

@khriskooper code contains an obvious bug: it flips array twice i.e. effectively does nothing. To flip array you should iterate only half of the indices. Try something like this:

private void flipHorizontally() {
    for (int y = 0; y < totalY; y++) {
        for (int x = 0; x < totalX/2; x++) {
            String tmp = fields[totalX-x-1][y].getText();
            fields[totalX-x-1][y].setText(fields[x][y].getText());
            fields[x][y].setText(tmp);
        }
    }
}


private void flipVertically() {
    for (int x = 0; x < totalX; x++) {
        for (int y = 0; y < totalY/2; y++) {
            String tmp = fields[x][totalY - y - 1].getText();
            fields[x][totalY - y - 1].setText(fields[x][y].getText());
            fields[x][y].setText(tmp);
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download