Sort JButtons in JPanel

Joanmi :

I am creating a chess game using Java, everything was fine when I saw that the JButtons are not added to the JPanel in order, that is, the (0,0) is not in the same position as it would be using System.out.Println Does anyone know how I could solve it?

private void configurarCaselles() {
    Insets marge = new Insets(0, 0, 0, 0);
    for (int i = 0; i < t.getTaulerCaselles().length; i++) {
        for (int j = 0; j < t.getTaulerCaselles()[0].length; j++) {
            Casella_Grafic c = t.getFitxaGrafic(i, j);
            c.setMargin(marge);

            ImageIcon icon = new ImageIcon(new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
            c.setIcon(icon);
            if ((i % 2 == 1 && j % 2 == 1) || (i % 2 == 0 && j % 2 == 0)) {
                c.setBackground(Color.WHITE);
            } else {
                c.setBackground(Color.BLACK);
            }
        }
    }
    chessBoard.add(new JLabel(""));
    for (int i = 0; i < 8; i++) {
        chessBoard.add(new JLabel(COLS.substring(i, i + 1), SwingConstants.CENTER));

    }

    for (int j = 0; j < 8; j++) {
        for (int i = 0; i < 8; i++) {
            switch (i) {
                case 0:
                    chessBoard.add(new JLabel("" + (9 - (j + 1)), SwingConstants.CENTER));
                default:
                    chessBoard.add(t.getFitxaGrafic(i, j));
            }
        }
    }
}

enter image description here

enter image description here

Icons Extracted here

Marco R. :

Apparently you are iterating your double array of JButtons over rows then over columns (top to bottom, then left to right) when adding the to the chessBoard:

chessBoard.add(t.getFitxaGrafic(i, j));

when it should be the opposite (columns then rows), so you just need to swap the i and j:

chessBoard.add(t.getFitxaGrafic(j, i));

Hope this helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76802&siteId=1