Java/Esempi/JFormattedTextField

Wikibooks, manuali e libri di testo liberi.

Ecco un semplice esempio di come si può usare una JFormattedTextField di Swing.

La finestra è stata creata al volo con il gui builder di netbeans e non ho inserito alcun codice per centrarla nello schermo.


import java.util.Locale;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
 
/*
 * NewJFrame.java
 *
 * Created on 27 settembre 2006, 8.31
 */
 
/**
 *
 * @author  Fabrizio P.
 */
public class NewJFrame extends javax.swing.JFrame {
 
    /** Creates new form NewJFrame */
    public NewJFrame() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
 
        initComponents();
        this.setTitle("Nominativo utente : (in attesa...) ");
 
 
        jtfName.setInputVerifier(new CustomValueVerifier());
        jtfName.setDocument(new CustomFilter());
 
        jtfSurname.setInputVerifier(new CustomValueVerifier());
        jtfSurname.setDocument(new CustomFilter());
 
 
    }
 
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtfName = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfSurname = new javax.swing.JFormattedTextField();
        bttSend = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setText("Inserisci il tuo nome:");
 
        jLabel2.setText("e  il tuo cognome :");
 
        bttSend.setText("Esegui test");
        bttSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttSendActionPerformed(evt);
            }
        });
 
        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(10, 10, 10)
                                .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jtfName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                            .add(jtfSurname, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, bttSend, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jtfName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jtfSurname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(bttSend)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
 
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>                        
 
    private void bttSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
 
        if (evt.getSource() instanceof JButton)
            if (jtfName.getValue() != null && jtfSurname.getValue() != null){
            NewJFrame.this.setTitle("Ultimo utente inserito : " + jtfSurname.getText() + " " + jtfName.getText());
            jtfName.setText("");
            jtfName.setValue(null);
            jtfSurname.setText("");
            jtfSurname.setValue(null);
            }
 
    }                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JButton bttSend;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JFormattedTextField jtfName;
    private javax.swing.JFormattedTextField jtfSurname;
    // End of variables declaration                   
 
}
 
class CustomFilter extends DefaultStyledDocument{
    /*
     * Controllo che il contenuto dei JFormattedTextField non superi i 25 caratteri.
     */
    public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
        /*
         * str rappresenta la stringa che sta per essere scritta nel componente.
         * Questo metodo infatti è chiamato prima di inserire del testo nel documento.
         */
        int strLen = str.length();
        int docLen = this.getLength();
        if (docLen + strLen > CustomFilter.MAX_DIM)
            if (docLen > CustomFilter.MAX_DIM)
                super.insertString(offset, getText(0,CustomFilter.MAX_DIM), a); // scrive la stringa di testo nel documento
            else{
            int dimTextToSend = CustomFilter.MAX_DIM - docLen;
            super.insertString(offset, str.substring(0,dimTextToSend), a);
            } else
                super.insertString(offset, str, a);
    }
    private static final int MAX_DIM = 25;
}
 
 
 
class CustomValueVerifier extends InputVerifier{
 
    public boolean verify(JComponent input) {
        /**
         * verifica che sia stato inserito del testo nel componente JFormattedTextField
         * e che contenga solo lettere o . In caso contrario il componente riottiene il focus
         **/
        JFormattedTextField jtf = (JFormattedTextField) input;
        String text = jtf.getText().trim();
        if (!text.equals("")){
            for (int i=0; i<text.length();i++){
                char ch = text.charAt(i);
                if(!Character.isLetter(ch) && !( i>0 && Character.isSpaceChar(ch)))
                    return false;
            }
            jtf.setValue(text.toUpperCase(Locale.ITALY));
            return true;
        }
        jtf.setValue(null);
        return false;
    }
}
 
/*******************************************************************************************************************/

Strumenti personali