Pessoal, estou com o seguinte problema:
Digito em um campo formatado uma entrada que resulta neste valor 11.111.111/1111-11
Utilizo uma função (que tem como entrada o valor acima, e que retorna String) que remove os caracteres especiais, no caso retorna 11111111111111
String retorno = this.removeCaracEspeciais(entradaDados.getText().toString());
O problema está quando tento fazer a alteração de tipo String para int, como está na linha abaixo:
int retornoInt = Integer.parseInt( retorno);
Segue código completo abaixo:
Toda ajuda é bem vinda, vlw.
package projetotestemaskara;
import javax.swing.text.MaskFormatter;
/**
*
-
@author Ricardo
*/
public class NewJFrame extends javax.swing.JFrame {/**
- Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
@SuppressWarnings(“unchecked”) // private void initComponents() {
botaoProcessar = new javax.swing.JButton(); saidaDados = new javax.swing.JLabel(); entradaDados = new javax.swing.JFormattedTextField(setMascara("##.###.###/####-##")); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); botaoProcessar.setText("jButton1"); botaoProcessar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoProcessarActionPerformed(evt); } }); saidaDados.setText("saida"); entradaDados.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { entradaDadosActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(saidaDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(entradaDados) .addComponent(botaoProcessar, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)) .addContainerGap(184, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(89, Short.MAX_VALUE) .addComponent(entradaDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46) .addComponent(botaoProcessar) .addGap(43, 43, 43) .addComponent(saidaDados) .addGap(65, 65, 65)) ); pack();
}//
private void entradaDadosActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
private void botaoProcessarActionPerformed(java.awt.event.ActionEvent evt) {
String retorno = this.removeCaracEspeciais(entradaDados.getText().toString()); saidaDados.setText(retorno); int retornoInt = Integer.parseInt( retorno); System.out.println( retornoInt );
}
/**
-
@param args the command line arguments
/
public static void main(String args[]) {
/- Set the Nimbus look and feel
/
//
/ - 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/*
-
Create and display the form
*/
java.awt.EventQueue.invokeLater({new Runnable()public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton botaoProcessar; private javax.swing.JFormattedTextField entradaDados; private javax.swing.JLabel saidaDados; // End of variables declaration
- Set the Nimbus look and feel
public MaskFormatter setMascara(String mascara){
//para a aplicação no textField //# = qualquer numero válido //U = qualquer caractere, as letras minusculas são formatadas em maiuscula. //L = qualquer caractere, as letras maiusculas são formatadas em minusculas. //A = qualquer caractere ou numero. MaskFormatter mask = null;
try{
mask =new MaskFormatter(mascara);}catch(java.text.ParseException ex){}
return mask;
}
public String removeCaracEspeciais(String str){
//Troca os caracteres especiais da string por "" String[] caracteresEspeciais = {"\\.", ",", "-", ":", "\\(", "\\)", "ª", "\\|", "\\\\", "°", "/"}; for (int i = 0; i < caracteresEspeciais.length; i++) { str = str.replaceAll(caracteresEspeciais[i], ""); } /** Troca os espaços no início por "" **/ str = str.replaceAll("^\\s+", ""); /** Troca os espaços no início por "" **/ str = str.replaceAll("\\s+$", ""); /** Troca os espaços duplicados, tabulações e etc por " " **/ str = str.replaceAll("\\s+", " "); return str;
}
- Creates new form NewJFrame
}