viernes, 23 de mayo de 2014

Controles Swing: Botones de radio, casillas verificación, spinner, slider,...

Continuamos viendo el uso de controles Swing en java, para ello hacemos una aplicación muy sencilla que permite modificar el estilo, tamaño y tipo de letra de un área de texto.
La ventana de la aplicación será algo como:

y el código (prestad atención en que alguno de los eventos llaman ya a la función p.e. cambiarTamano pero otros controles tratan el evento directamente,...es lo explicado en clase, todas deberían llamar al método para no estar repitiendo código y tratando lo mismo en veinte sitios ya que dificulta además de la programación el mantenimiento de las aplicaciones):





/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package explicacioncontroles;

import java.awt.Font;
import java.awt.font.TextAttribute;
import java.util.Map;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

/**
*
* @author Juan
*/
public class VentanaFuentes extends javax.swing.JFrame {

 
    /**
     * Creates new form VentanaFuentes
     */
    public VentanaFuentes() {
        initComponents();
        lblTamano.setText(String.valueOf(sldTamano.getValue()));
        ta1.setFont(ta1.getFont().deriveFont((float)sldTamano.getValue()));
        rbSansSerif.setSelected(true);
    }

    /**
     * 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() {

        grpFuentes = new javax.swing.ButtonGroup();
        jScrollPane2 = new javax.swing.JScrollPane();
        ta2 = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        ta1 = new javax.swing.JTextArea();
        btnCopiar = new javax.swing.JButton();
        panFuentes = new javax.swing.JPanel();
        rbMonoSpace = new javax.swing.JRadioButton();
        rbSansSerif = new javax.swing.JRadioButton();
        rbSerif = new javax.swing.JRadioButton();
        panEstilo = new javax.swing.JPanel();
        cbSubrayado = new javax.swing.JCheckBox();
        cbNegrita = new javax.swing.JCheckBox();
        cbCursiva = new javax.swing.JCheckBox();
        panTamano = new javax.swing.JPanel();
        sldTamano = new javax.swing.JSlider();
        spnTamano = new javax.swing.JSpinner();
        lblTamano = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Explicación controles Swing con Fuentes");

        ta2.setColumns(20);
        ta2.setRows(5);
        jScrollPane2.setViewportView(ta2);

        ta1.setColumns(20);
        ta1.setRows(5);
        jScrollPane1.setViewportView(ta1);

        btnCopiar.setMnemonic('C');
        btnCopiar.setText("Copiar Selección");
        btnCopiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCopiarActionPerformed(evt);
            }
        });

        panFuentes.setBorder(javax.swing.BorderFactory.createTitledBorder("Fuente:"));

        grpFuentes.add(rbMonoSpace);
        rbMonoSpace.setText("MonoSpace");
        rbMonoSpace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbMonoSpaceActionPerformed(evt);
            }
        });

        grpFuentes.add(rbSansSerif);
        rbSansSerif.setText("Sans Serif");
        rbSansSerif.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbSansSerifActionPerformed(evt);
            }
        });

        grpFuentes.add(rbSerif);
        rbSerif.setText("Serif");
        rbSerif.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbSerifActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panFuentesLayout = new javax.swing.GroupLayout(panFuentes);
        panFuentes.setLayout(panFuentesLayout);
        panFuentesLayout.setHorizontalGroup(
            panFuentesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panFuentesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panFuentesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rbSansSerif)
                    .addComponent(rbMonoSpace)
                    .addComponent(rbSerif))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        panFuentesLayout.setVerticalGroup(
            panFuentesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panFuentesLayout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(rbMonoSpace)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbSansSerif, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbSerif)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panEstilo.setBorder(javax.swing.BorderFactory.createTitledBorder("Estilo:"));
        panEstilo.setToolTipText("Pulsar para cambiar el estilo de la primera área de texto");

        cbSubrayado.setMnemonic('S');
        cbSubrayado.setText("Subrayado");
        cbSubrayado.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbSubrayadoItemStateChanged(evt);
            }
        });

        cbNegrita.setMnemonic('N');
        cbNegrita.setText("Negrita");
        cbNegrita.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbNegritaItemStateChanged(evt);
            }
        });

        cbCursiva.setMnemonic('K');
        cbCursiva.setText("Cursiva (K)");
        cbCursiva.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbCursivaItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout panEstiloLayout = new javax.swing.GroupLayout(panEstilo);
        panEstilo.setLayout(panEstiloLayout);
        panEstiloLayout.setHorizontalGroup(
            panEstiloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panEstiloLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panEstiloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbCursiva)
                    .addComponent(cbNegrita)
                    .addComponent(cbSubrayado))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        panEstiloLayout.setVerticalGroup(
            panEstiloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panEstiloLayout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(cbNegrita)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbCursiva)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbSubrayado)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        panTamano.setBorder(javax.swing.BorderFactory.createTitledBorder("Tamaño:"));

        sldTamano.setMajorTickSpacing(10);
        sldTamano.setMaximum(50);
        sldTamano.setMinorTickSpacing(2);
        sldTamano.setPaintLabels(true);
        sldTamano.setPaintTicks(true);
        sldTamano.setSnapToTicks(true);
        sldTamano.setValue(14);
        sldTamano.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sldTamanoStateChanged(evt);
            }
        });

        spnTamano.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        spnTamano.setModel(new javax.swing.SpinnerNumberModel(14, 0, 50, 1));
        spnTamano.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spnTamanoStateChanged(evt);
            }
        });

        lblTamano.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTamano.setText("0");

        javax.swing.GroupLayout panTamanoLayout = new javax.swing.GroupLayout(panTamano);
        panTamano.setLayout(panTamanoLayout);
        panTamanoLayout.setHorizontalGroup(
            panTamanoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panTamanoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sldTamano, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
            .addGroup(panTamanoLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(spnTamano, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(lblTamano, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panTamanoLayout.setVerticalGroup(
            panTamanoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panTamanoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sldTamano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panTamanoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTamano, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(spnTamano)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(panFuentes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(panEstilo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(panTamano, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(216, 216, 216)
                        .addComponent(btnCopiar)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(panFuentes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panEstilo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panTamano, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnCopiar)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19))
        );

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

    private void btnCopiarActionPerformed(java.awt.event.ActionEvent evt) {                                         
      
        ta2.setText(ta1.getSelectedText());
        ta2.setFont(ta1.getFont());
    }                                        

    private void cambiarFuente(String fuente)
    {
        Font fu,fuenteDeTa1;
        fuenteDeTa1= ta1.getFont();
       
        fu = new Font(fuente,ta1.getFont().getStyle(),fuenteDeTa1.getSize());
        ta1.setFont(fu);
    }
    private void rbMonoSpaceActionPerformed(java.awt.event.ActionEvent evt) {                                           
        Font fuente;
       
        fuente = new Font(Font.MONOSPACED,ta1.getFont().getStyle(),ta1.getFont().getSize());
        ta1.setFont(fuente);

    }                                          

    private void rbSansSerifActionPerformed(java.awt.event.ActionEvent evt) {                                           
        cambiarFuente(Font.SANS_SERIF);
    }                                          

    private void rbSerifActionPerformed(java.awt.event.ActionEvent evt) {                                       
      cambiarFuente(Font.SERIF);  // TODO add your handling code here:
    }                                      

    private void cambiarEstilo(java.awt.event.ItemEvent evt)
    {
        JCheckBox origen;
       
        origen = (JCheckBox) evt.getSource();
          
              
        if (origen==cbCursiva)
            if ( cbCursiva.isSelected())
            {
                ta1.setFont(ta1.getFont().deriveFont(ta1.getFont().getStyle()+Font.ITALIC));
            }
            else
                ta1.setFont(ta1.getFont().deriveFont(ta1.getFont().getStyle()-Font.ITALIC));

    }
    private void cbNegritaItemStateChanged(java.awt.event.ItemEvent evt) {                                          
        Font fuente,fuenteDeTa1;
        fuenteDeTa1 = ta1.getFont();
       
        if(!cbNegrita.isSelected())
        {
            fuente = fuenteDeTa1.deriveFont(fuenteDeTa1.getStyle()-Font.BOLD) ;
        }
            else fuente = ta1.getFont().deriveFont(ta1.getFont().getStyle()+Font.BOLD) ;
        ta1.setFont(fuente);
       
        ta2.setText(""+fuente.getStyle());
    }                                         

    private void cbCursivaItemStateChanged(java.awt.event.ItemEvent evt) {
        cambiarEstilo(evt);
    }

    private void cbSubrayadoItemStateChanged(java.awt.event.ItemEvent evt) {
     
        Map atributos = ta1.getFont().getAttributes();
        if (cbSubrayado.isSelected()) {
            atributos.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        }
        else {
            atributos.put(TextAttribute.UNDERLINE,-1);
          }
        ta1.setFont(ta1.getFont().deriveFont(atributos));
    }

    private void sldTamanoStateChanged(javax.swing.event.ChangeEvent evt) {
        cambiarTamano(sldTamano.getValue());        // TODO add your handling code here:
      
       
    }
    private void cambiarTamano(int nuevoTamano)
    {
        try {
            sldTamano.setValue(nuevoTamano);// TODO add your handling code here:
            lblTamano.setText(String.valueOf(String.valueOf(nuevoTamano))); 
            spnTamano.setValue(sldTamano.getValue());
           
        } catch (Exception e) {
            JOptionPane.showMessageDialog(panTamano, "Sólo números: "+e.getMessage());
        }
        ta1.setFont(ta1.getFont().deriveFont((float) nuevoTamano));
    }
   
    private void spnTamanoStateChanged(javax.swing.event.ChangeEvent evt) {
        try {
            cambiarTamano((int)spnTamano.getValue());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(panTamano, "Sólo números en spnTamanoStateChanged: "+e.getMessage());
        }

    }

    /**
     * @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(VentanaFuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaFuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaFuentes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaFuentes.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 VentanaFuentes().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnCopiar;
    private javax.swing.JCheckBox cbCursiva;
    private javax.swing.JCheckBox cbNegrita;
    private javax.swing.JCheckBox cbSubrayado;
    private javax.swing.ButtonGroup grpFuentes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblTamano;
    private javax.swing.JPanel panEstilo;
    private javax.swing.JPanel panFuentes;
    private javax.swing.JPanel panTamano;
    private javax.swing.JRadioButton rbMonoSpace;
    private javax.swing.JRadioButton rbSansSerif;
    private javax.swing.JRadioButton rbSerif;
    private javax.swing.JSlider sldTamano;
    private javax.swing.JSpinner spnTamano;
    private javax.swing.JTextArea ta1;
    private javax.swing.JTextArea ta2;
    // End of variables declaration
}