How to make a grid with squares?

3

I would like to do something like this here, a Grid based on an array (and based on the value of the array, set a color to the corresponding cell), and I can manipulate it with the mouse.

    
asked by anonymous 17.09.2017 / 15:39

1 answer

4

Based on an example of chessboard , I made this example of grid filled with JLabels , where clicking on any of them changes the background color to black. Using it as a base, you can better develop your idea.

This class will create a panel of populated JLabels in GridLayout :

class GridPane extends JPanel {

    private static final long serialVersionUID = 1L;
    private int rows;
    private int column;

    private JLabel[][] squares;

    public GridPane(int rows, int column) {
        this.rows = rows;
        this.column = column;
        this.setLayout(new GridLayout(rows, column));
        this.squares = new JLabel[this.rows][this.column];

        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.column; c++) {
                SquareLabel square = new SquareLabel();
                this.squares[r][c] = square;
                this.add(square);
            }
        }
    }
}

I also created a class, the part called SquareLabel pro in case you want to customize something in each square:

class SquareLabel extends JLabel {

    private static final long serialVersionUID = 1L;

    public SquareLabel() {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.black, 1));
        addMouseListener(new ClickChangeColor());
    }
}

I have also separated the listener , although for the example neither it would be necessary, but with it already created, it facilitates addition of other actions that may be related to the mouse:

class ClickChangeColor extends MouseAdapter {

    boolean clicked = false;

    @Override
    public void mouseClicked(MouseEvent e) {

        clicked = !clicked;
        JLabel square = (JLabel) e.getSource();
        Color color = clicked ? Color.black : square.getParent().getBackground();
        square.setBackground(color);
    }
}

Running:

Imadetheexecutableexamplethatcanbetestedin Github .

    
17.09.2017 / 18:32