3
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:
I made executable example that can be tested on Github.
Do with what? I think the question is too broad.
– user28595
I’ll make it better, but in case you’re asking the language, it’s Java (it’s in the tags).
– Lucas Caresia
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.
– user28595
Any one I accept, I just need to do this, the one you think fits best can put as an answer.
– Lucas Caresia
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.
– user28595