0

I recently run in to same problem as this guy 4 years before. He get some answers there but non of it work either for him or me and then the question was not updated anymore. How to get string from JTextField and save it in variable?

The point is to check what is typed in textfield and if, like in example is yet decimal dot in the TextField, then consume event and not allow to add second decimal dot.

Main problem I figured out is that I need to add this inside the key event as shown belox. But this. statement inside the event reffers to event itself and not on JTextField.So I need to find bypass or other solution how to write getText statement

String text = this.getText().toString();

if someone have ideas of how to improve code as well I'm opened to any suggestions except for rewriting it as formatted field because the user experience is a little different, from the point where I was trying formatted field.

public class TxtfNumber extends JTextField {

 String text = this.getText().toString();  

 public TxtfNumber(){

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent evt) {
                switch (evt.getID()) {
                    case KeyEvent.KEY_TYPED:
                            String text = this.getText().toString();
                            if(evt.getKeyChar()=='.'&& text.contains(".")){
                               evt.consume();
                                } 
                           
                            
                    }

                    return false;
            }
        });
}
} 
Rjelinek
  • 26
  • 6
  • 1
    *I'm trying to make a custom text field for currencies with decimals etc.* If you're using a JTextField to output a currency amount, use the format method of the String class to format the text. If you're using a JTextField for input, use a [JFormattedTextField](https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html). Don't try to create your own Swing components unless you have much more experience. – Gilbert Le Blanc Jan 14 '21 at 18:13
  • How do you expect it to have a value when you declare a class level variable that gets instantiated when the class is created, unless it has text somehow before its even created its pretty obvious it will be empty. You don't give any minimal reproducible example or explain what you are trying to achieve besides saying that a formatted textfield won't work for you and you have issues calling `getText`. Also you do know java is open source, so you could look at how the `JFormattedTextField` works and borrow code from there. At a minimum you should have a `DocumentFilter` – David Kroukamp Jan 14 '21 at 18:20
  • [JFormattedTextField source code](http://fuseyism.com/classpath/doc/javax/swing/JFormattedTextField-source.html) – David Kroukamp Jan 14 '21 at 18:25
  • no I firstly run it, write some random nubers in field. But the outcome after every stroke is still null. Sorry for not making everithing clear I'm new here. the whole point of this text field is to minimise inputs to minus sign, decimals dot and number. I don't want to use forrmated text field beceuse it have preformated decimal dot which you need to skip by arrow key what will eventually slow typing. I'm making it for small accounting program where is mainly used numeric keypad where you have dot key – Rjelinek Jan 14 '21 at 18:51
  • Use a `DocumentFilter` as I have said here is an example https://stackoverflow.com/a/14174868/1133011 – David Kroukamp Jan 14 '21 at 19:39
  • For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). **BTW:** 1) *"I'm trying to make custom text field for currencies with decimals"* I'd use a `JSpinner` with a `SpinnerNubnerModel` for that. 2) *"I recently run in to same problem as this guy 4 years before"* What guy? Link please. – Andrew Thompson Jan 15 '21 at 01:02
  • yesterday I had a great diskusion here about problem. the main problem is that you need to call String text = this.getText().toString(); inside the key event. but there is a problem that statement this inside the event is reffering to event itself and not to textfield. so you need to find how to declare that you're reffering to JTextField. sorry for not adding link, it was pretty much same problem I asume, cos he also needed to reffer on JTestfield inside event. here it is. https://stackoverflow.com/questions/36936186/how-to-get-string-from-jtextfield-and-save-it-in-variable?r=SearchResults – Rjelinek Jan 15 '21 at 02:34
  • 1) Tip: Add @DavidKroukamp (or whoever, the `@` is important) to *notify* the person of a new comment. 2) As to the edits & new comments. I'll look closely at them, once you have posted an MRE / SSCCE, and I have it compiled in my IDE. – Andrew Thompson Jan 15 '21 at 03:34

1 Answers1

0

SOLUTION

I accidentally run in solution when I used lambda expression. The formula you need to use is the name of class then .this. So in this case,

String text = TxtfNumber.this.getText().toString();

is the solution.

But eventually, when I know how to implement JTextField, I no longer need a solution by string. So I'm giving the whole code here for later use. Feel free to use it as Choose Bean component.

It restricts the user to use only one minus sign at the start of the text, one decimal dot anywhere and then type in two decimal numbers.

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;


public class TxtfNumber extends JTextField {



    public TxtfNumber(){

 KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
     @Override
     public boolean dispatchKeyEvent(KeyEvent evt) {
         switch (evt.getID()) {
             case KeyEvent.KEY_TYPED:
                 //restricts input charactes
                 if(!Character.isDigit(evt.getKeyChar()) && (evt.getKeyChar()!='.') && (evt.getKeyChar()!='-') && (evt.getKeyChar()!=','))
                     evt.consume();
                 
                 //change , and . for securing of different keyboard language
                 if (evt.getKeyChar()==',')
                     evt.setKeyChar('.');
                 
                 //allow only one decimal dot in text
                 if (evt.getKeyChar()=='.' && TxtfNumber.this.getText().contains(".")) 
                     evt.consume();
                 
                 //allow minus sign only at the start of text
                 if (evt.getKeyChar()=='-' && TxtfNumber.this.getText().length() != 0)
                     evt.consume();
                 
                 //allow two decimal numbers after dot
                 for (int i = -1; (i = TxtfNumber.this.getText().indexOf(".", i + 1)) != -1; i++) {
                     if (i+3 == TxtfNumber.this.getText().length()) 
                         evt.consume();
                 }
                 break;
         }
         return false;
     }
 });

    }
}; 
The Amateur Coder
  • 789
  • 3
  • 11
  • 33
Rjelinek
  • 26
  • 6