Red de conocimiento de abogados - Derecho de sociedades - Cómo configurar el cuadro de texto en java swing para ingresar solo números

Cómo configurar el cuadro de texto en java swing para ingresar solo números

Esto se puede lograr usando el control JFormattedTextField y keyReleased en java swing. El siguiente código de cuadro de texto solo puede ingresar números:

import java.text.ParseException

importar javax.swing.JFormattedTextField;

importar javax.swing.JFrame;

importar javax.swing.JPanel;

/**

*

* @author Administrador

*/

clase pública JFormattedText extiende JFrame {

texto privado JFormattedTextField;

public JFormattedText() {

panel JPanel = nuevo JPanel();

texto = nuevo JFormattedTextField(nuevo java.text.DecimalFormat("#0" ) );

// text = new JFormattedTextField();

// text.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter( new java.text.DecimalFormat("#0"))));

text.setFont(new java.awt.Font("宋体", 0, 12) // NOI18N

text.setMaximumSize(new java.awt.Dimension(50, 21));

text.setMinimumSize(new java.awt.Dimension(50, 21)); p > text.setPreferredSize(new java.awt.Dimension(50, 21));

//Filtrar los caracteres de entrada

text.addKeyListener(new java.awt.event. KeyAdapter () {

public void keyReleased(java.awt.event.KeyEvent evt) {

String old = text.getText();

JFormattedTextField. AbstractFormatter formateador = text.getFormatter();

if (!old.equals("")) {

if (formatter != null) {

String str = text.getText();

prueba {

long page = (Long) formatter.stringToValue( str);

text.setText(página "");

} catch (ParseException pe) {

text.setText("1");/ La excepción /Parse establece directamente el valor en el cuadro de texto en 1

}

}

}

}

});

panel.add(texto);

this.add(panel);

this.setBounds(200, 100, 100, 100 );

}

public static void main(String[] arg) {

new JFormattedText().setVisible(true);

}

}