I have create a custom JTextFields that can accept only number values.
So I have this:
package com.mcsolution.common.Componenti_Swing;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import com.mcsolution.common.supporto.VisualMessage;
public class DoubleTextFieldFormat extends TextFieldFormat{
/**
*
*/
private static final long serialVersionUID = 8856130645860365803L;
public DoubleTextFieldFormat(){
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (!isNumber(ch) && !isValidSignal(ch) && !validatePoint(ch) && ch != '\b') {
e.consume();
}
}
});
}
public DoubleTextFieldFormat(Font font,Boolean isSelectedAll,Integer horizzontalAlignment,
Integer numberCharacter,String text,Dimension preferredSize,
Boolean isEditable){
if(font!=null)
this.setFont(font);
if(isSelectedAll){
this.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e){
selectAll();
}
public void focusLost(FocusEvent e){
}
});
}
if(horizzontalAlignment!=null)
this.setHorizontalAlignment(horizzontalAlignment);
if(numberCharacter!=null)
this.setDocument(new PersonalizzaJtextField(numberCharacter));
if(text!=null)
this.setText(text);
if(preferredSize!=null)
this.setPreferredSize(preferredSize);
if(isEditable!=null)
this.setEditable(isEditable);
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (!isNumber(ch) && !isValidSignal(ch) && !validatePoint(ch) && ch != '\b') {
e.consume();
}
}
});
}
private boolean isNumber(char ch){
return ch >= '0' && ch <= '9';
}
private boolean isValidSignal(char ch){
if( (getText() == null || "".equals(getText().trim()) ) && ch == '-'){
return true;
}
return false;
}
private boolean validatePoint(char ch){
if(ch != '.'){
return false;
}
if(getText() == null || "".equals(getText().trim())){
setText("0.");
return false;
}else if("-".equals(getText())){
setText("-0.");
}
return true;
}
public Double getValue(){
try{
String valore = this.getText();
valore= valore.replaceAll(",", ".");
return Double.parseDouble(valore);
}catch(Exception e){
VisualMessage.getErrore();
return null;
}
}
}
Now if I want retrieve the value I use this code:
Double val = myTextField.getValue();
This method works not every times.
For example if I have this value into TextField 1.900,50 if have an errore.
How can I convert the value in this format x.xxx,xx?