JtextField + PlainDocument not returning the string in the box...
Hi,
I am having a minor problem with the code below.
as you can tell, what Ive done is created a JTextField that can have a maximum of 3 or 4 numbers (with or without the ".") It has a default value, that is set if the field is left blank (or if it is blank and the user is trying to type letters into the field)
Ive done this by extending JTextField and setting the model to my extended PlainDocument class. (see code below)
The only problem is that in my main application is trying to get the value of the object. so we call
getText()
this unforunately does not return the value in the text box, but rather the default value that is set at its instantiation...
any ideas on how to get the value of that has been entered into the box?
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
public class TextField3Nums extends JTextField implements FocusListener{
public static String m_strVal;
public TextField3Nums(String str) {
super(str);
m_strVal = str;
this.addFocusListener(this);
}
public void focusGained(FocusEvent e) {}; // not needed
public void focusLost(FocusEvent e) {
// do checking
if (this.getText().length() == 0){
//set default value on exit from field
this.setText(m_strVal);
}
}
protected Document createDefaultModel() {
return new PlainDoc3Nums();
}
static class PlainDoc3Nums extends PlainDocument {
public void insertString(int iOffset, String str, AttributeSet ats)
throws BadLocationException {
char[] insertChars = str.toCharArray();
boolean valid = true;
boolean fit = true;
if (insertChars.length + getLength() <= 4) {
for (int i = 0; i < insertChars.length; i++) {
if (insertChars == '.'){
valid = true;
break;
}
if (!Character.isDigit(insertChars)) {
valid = false;
break;
}
//limit to 3 numbers only, . not to be included
if (Character.isDigit(insertChars)){
if (insertChars.length + getLength() == 4){
if (!this.getText(0,3).contains(".")){
valid = false;
break;
}
}
}
}
}
else{
fit = false;
}
if (fit && valid){
super.insertString(iOffset, str, ats);
}else if (!fit){
//do nothing
}
if (getLength() == 0){
super.insertString(iOffset, m_strVal, ats);
}
}
protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng){
super.removeUpdate(chng);
/*if (getLength() == 1){
try{
insertString(1, m_strVal, null);
}catch(BadLocationException ble){
}
}*/
}
}
}

