Matrices de botones

Trojanus
26 de Abril del 2006
hola necesito una especie de matriz con botones, es decir simular un juego de ajedrez pero necesito crear el cuadro con puro botones y lo mejor seria con unamtriz de botones pero no se com hacerlo, cualquier ayuda se las agradecira.

x
26 de Abril del 2006
crea tu matriz de MxN botones asi:

JButton[][] matrix = new JButton[M][N];
//eso te crea una matriz de MxN
y ahora inicializa cada JButton independientemente con un doble for
for(int i = 0; i < matrix.length; ++i
for(int j = 0; j < matrix[i].length; ++j)
matrix[i][j] = new JButton("lo que quieras poner");

eso es solo para poder manejarlos, ya si quieres acomodarlos en una rejilla puedes usar el GridLayout
para meterlos

rubece
26 de Abril del 2006
Esto te podría servir como ejemplo:

import javax.swing.*;
import java.awt.*;

public class Tablero extends JFrame {
JButton[][] tablero = new JButton[8][8];

public Tablero() {
JPanel panel = new JPanel();

panel.setLayout(new GridLayout(tablero.length, tablero[0].length));
for (int i = 0; i < tablero.length; i++)
for (int j = 0; j < tablero[0].length; j++) {
tablero[i][j] = new JButton("Botón " + i + ", " + j);
panel.add(tablero[i][j]);
}
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(panel);
this.pack();
this.setVisible(true);
}

public static void main(String[] args) {
new Tablero();
}
}

El programa solo crea los botones y lo muestra. Si pulsas los botones no pasa nada. Bueno si tienes duda, pregunta, Que te vaya bien. Hasta luego.


14 de Mayo del 2016

Buen Día Rubece.

Me surge una duda, este for que tu colocas: 

for (int i = 0; i<chessboard.length; i++){// Filas
for (int j=0; j<chessboard[0].length; j++){// Columnas
chessboard[i][j] = new JButton ("Boton"+i+","+j);

afecta solo el text del JBoton, pero si deseo que afecte el name del JButton

como se haria, Gracias de antemano.