How to make a grid with squares?

Asked

Viewed 403 times

3

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

inserir a descrição da imagem aqui

  • Do with what? I think the question is too broad.

  • I’ll make it better, but in case you’re asking the language, it’s Java (it’s in the tags).

  • Which is java I saw, but you can even do this in text mode. You didn’t set a starting point. There are N Java Apis to try this.

  • Any one I accept, I just need to do this, the one you think fits best can put as an answer.

  • Just close the scope a little bit to some java graphic API, like swing, so you can answer without it being closed. If I add this tag, it can be considered change of intention by moderation.

1 answer

4

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

This class will create a populated Jlabels panel in a 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 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 also separated the Listener, although for the example would not even be necessary, but with it already created, facilitates adding 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:

GIF Executável

I made executable example that can be tested on Github.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.