lunes, 12 de mayo de 2014

Agregando botones gridLayout y clase manejador

Agregamos a una ventana una serie de botones cuyo manejador es la clase manejador. La ventana ha sido creada desde netBeans pero el panel es el genérico.

package cuadradosadivina;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;




/**
*
* @author juan
*/
public class VentanaGridLayout extends javax.swing.JFrame {

   
    /**
     * Creates new form VentanaGridLayout
     */
    public VentanaGridLayout() {
        initComponents();
        AnhadirBotones(16,4);
        pack();
    }
    private void AnhadirBotones(int numBotones,int numfilas){
        panTablero.removeAll();
        panTablero.setLayout(new GridLayout(numfilas,0));
       
        boton = new JButton [numBotones];
        for (int i = 0; i < numBotones; i++) {
            boton[i]=new JButton();
            boton[i].setName(String.valueOf(i));
            boton[i].setText("Botón: "+i);
            boton[i].setToolTipText("Ratón situado sobre el botón número "+ i);
            boton[i].addActionListener(new manejador());
            panTablero.add(boton[i]);
        }
       
       
        repaint();
       
    }
    /**
     * 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() {

        jButton1 = new javax.swing.JButton();
        panTablero = new javax.swing.JPanel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(800, 800));
        setMinimumSize(new java.awt.Dimension(400, 400));
        setPreferredSize(new java.awt.Dimension(400, 400));

        panTablero.setLayout(new java.awt.GridLayout(4, 0));
        getContentPane().add(panTablero, java.awt.BorderLayout.CENTER);

        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(VentanaGridLayout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaGridLayout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaGridLayout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaGridLayout.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 VentanaGridLayout().setVisible(true);
            }
        });
    }
    //Declaración de variables no de NetBeans
    private JButton [] boton;
   
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel panTablero;
    // End of variables declaration                  
}

class manejador implements ActionListener {
    manejador(){
       
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "has pulsado el botón"+e.getSource());
    }
}

No hay comentarios: