0

I'm writing a program using JavaFX and I currently have three TextFields. When you press enter while any of the text fields are focused, there is an EventHandler which calls the appropriate method for each field. There is no submit button because I want it to submit each input separately (that's just how I made the rest of the program) to be validated and return a String containing any errors in the input. If the users input is invalid, it resets it to the last valid value it had.

However, when testing I found that sometimes I just click somewhere else (such as the next field) rather than pressing enter, so I wanted to implement the same function as pressing enter but when the user clicks outside the field. There is a MouseClicked event on the root that I have attempted to make it submit the input for all of the fields at once which works, but if any field has not been filled in, then it will be unsuccessful and return an error message (which might confuse a user).

Additionally, if the user clicks inside the TextField again, say to delete something from the middle of the word, the event will be triggered and the field will be reset to the last valid value if the current input was invalid.

I've considered using a MouseExited event on each field, but I think that might be triggered by the cursor leaving the field, rather than a click outside of the field.

What would be a good way of doing this, while minimising the number of event methods in my program?

JolonB
  • 415
  • 5
  • 25
  • 1
    I suspect you want to [use a TextFormatter](https://openjfx.io/javadoc/11/javafx.controls/javafx/scene/control/TextInputControl.html#setTextFormatter%28javafx.scene.control.TextFormatter%29) rather than listening to mouse events. – VGR Dec 12 '18 at 04:21
  • 1
    Related and possibly helpful: [Focus Listener for JavaFX Nodes](https://stackoverflow.com/questions/21798183/focus-listener-for-javafx-nodes) – Ole V.V. Dec 12 '18 at 04:26
  • @OleV.V. I thought about that. Is there anyway to combine an EventHandler for when the user presses enter and a FocusListener? I'm probably going to add more TextFields and I don't want to fill my code with two events each (which do the exact same thing, just under different conditions). Essentially, at this point I have 3 fields which do 3 different things when you finish with them, but I don't want to have 3 EventHandlers and 3 FocusListeners to tell the program when they are finished with. I would rather have one each (3 total) that catches an enter key press and losing focus. – JolonB Dec 12 '18 at 19:45

0 Answers0