0

Tengo este form:

public class Tablero extends javax.swing.JFrame {

    private Container contenedor;
    private GridLayout layout;
    private JButton[][] botones;
    
    
    public Tablero() {
        initComponents(); 
    layout=new GridLayout(8,8);
    contenedor=getContentPane();
    contenedor.setLayout(layout);
    botones=new JButton[8][8];
    
       Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
      int height = pantalla.height;
      int width = pantalla.width;
      setSize(693, 557);        

      setLocationRelativeTo(null);
      
 
           ImageIcon icono = null;
        java.net.URL imgURL1 = Tablero.class.getResource("/imagenes/reina.jpg");
    
      
        if (imgURL1 != null) {
            icono = new ImageIcon(imgURL1); //Usa imgURL1 o imgURL2
        } else {
            System.out.println("No se pudo cargar la imagen.");
        }
        
        
        
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j <8; j++) {
               
                if (i==7) {
                    botones[i][j]=new JButton(icono);
                }else{
                    if (i==0) {
                        botones[i][j]=new JButton("0"); 
                        
                       
                    }else{
                         botones[i][j]=new JButton("0");
                    }
                    
                }
               
                contenedor.add(botones[i][j]);
            }
        }
     
      // contenedor.add(new JButton("siguiente"));
//      this.jPanel1.setBounds(0, 0, 512, 512);
//      this.jPanel1.setBackground(new java.awt.Color(190, 190, 190));
    }
//  private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {                                    
//      Dibujar t = new Dibujar(jPanel1.getGraphics(), this.jPanel1.getWidth());
//   }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 693, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 557, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tablero.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tablero.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tablero.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tablero.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tablero().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel36;
    private javax.swing.JPanel jPanel37;
    // End of variables declaration                   
}

El cual me hace un tablero con botones como se ve en la siguiente imagen: introducir la descripción de la imagen aquí

Como hago para mantener este tablero exactamente igual igual pero con la opción de agregar más controles (paneles,labels,botones) en la parte de abajo después del tablero.

1 respuesta 1

0

Simplemente debes de convertirlo de un formulario a un panel, de la siguiente manera:

package com.stackoverflow.es.question371169;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class Tablero extends javax.swing.JPanel {

    private Container contenedor;
    private GridLayout layout;
    private JButton[][] botones;

    public Tablero() {
        initComponents();
        layout = new GridLayout(8, 8);
        contenedor = this;
        contenedor.setLayout(layout);
        botones = new JButton[8][8];

        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
        int height = pantalla.height;
        int width = pantalla.width;
        setSize(693, 557);

        //setLocationRelativeTo(null);

        ImageIcon icono = null;
        java.net.URL imgURL1 = Tablero.class.getResource("/imagenes/reina.jpg");

        if (imgURL1 != null) {
            icono = new ImageIcon(imgURL1); //Usa imgURL1 o imgURL2
        } else {
            System.out.println("No se pudo cargar la imagen.");
        }

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {

                if (i == 7) {
                    botones[i][j] = new JButton(icono);
                } else {
                    if (i == 0) {
                        botones[i][j] = new JButton("0");

                    } else {
                        botones[i][j] = new JButton("0");
                    }

                }

                contenedor.add(botones[i][j]);
            }
        }

        // contenedor.add(new JButton("siguiente"));
//      this.jPanel1.setBounds(0, 0, 512, 512);
//      this.jPanel1.setBackground(new java.awt.Color(190, 190, 190));
    }
//  private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {                                    
//      Dibujar t = new Dibujar(jPanel1.getGraphics(), this.jPanel1.getWidth());
//   }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 693, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 557, Short.MAX_VALUE)
        );

        
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel36;
    private javax.swing.JPanel jPanel37;
    // End of variables declaration                   
}

Como habrás notado eliminas todas las referencias que haya a cosas que sean de JFrame

A partir de este momento puedes sin preocuparte embeberlo en tu frame principal, por ejemplo:

package com.stackoverflow.es.question371169;

public class ElAjedrez extends javax.swing.JFrame {

    /**
     * Creates new form ElAjedrez
     */
    public ElAjedrez() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tablero1 = new com.stackoverflow.es.question371169.Tablero();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(tablero1, java.awt.BorderLayout.CENTER);

        jButton1.setText("jButton1");

        jButton2.setText("jButton2");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 231, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(64, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ElAjedrez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ElAjedrez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ElAjedrez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ElAjedrez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ElAjedrez().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private com.stackoverflow.es.question371169.Tablero tablero1;
    // End of variables declaration                   
}

Yo lo hice con ayuda de netbeans, y se ve así en matisse que es el editor gráfico que tiene:

componente en el editor visual de netbeans

Ya ejecutándose el formulario se ve así:

componente de tablero de ajedrez ya embebido

Con esta solución evitas tener filas vacías que se renderizan, que es un problema que tiene gridlayout en ciertas condiciones particulares.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.