![]() |
JTextField problem
Hi everyone
I'm making a small program using Java. As part of this, the user is able to enter text in a JTextField (in a JPanel). My problem is, the only way that the actionlistener will activate is if a person entering text presses 'enter' on their keyboard. This works for testing, but for the actual program, it's counter-intuitive. Does anyone know a better way of entering text? Ideally it would update everytime the user enters even a single letter. |
I think a KeyListener would do the job (http://docs.oracle.com/javase/1.4.2/...yListener.html), instead of the actionlistener.
|
You were right about the KeyListener, it solved my problems.
Unfortunately, it also created one. The Backspace command it wonky. Here's how it works: (text in text box) (text stored in the class) name name nam nam (I typed in 'backspace') namw nam (I typed in 'w', but it didn't get stored in the class) namwg namw (I typed in 'g', and the 'w' appeared, but not the 'g') For some reason, after I type in backspace, the text box permanently loses a character when the KeyListener activates. |
It really is. Anyone know whats going wrong? And how to fix it?
|
Is the text in the class always supposed to match the text entered in the text field?
|
Thats how I want it to work, yes.
Ideally, the contents of the JTextField will always, instantly, update the String I store it in. |
Then the best approach to this is to share the model used for both of the text fields. This is a simple Document type, which can be prepopulated with data if desired. Since the Document will register the document listeners itself, you don't need to handle any events at all.
See this example (untested, but if necessary I can verify after): PHP Code:
|
Ok... I'm man enough to admit when I'm stumped.
I want to store the text (about 20 characters worth at maximum), in a string, from which I'll send it to various other classes. Why do I need a Document instead of a String? And why do I need 2 JTextFields? |
You don't need two text fields; that's simply what you specified. Or did I simply misunderstand the purpose of the example you have?
Going back through this, I believe that I misinterpreted your requirements. Instead of two inputs, you have a class you are intending to link to a text field. This is fine, but since strings are immutable in java, you can only trigger the update with a required string type using a listener of some sorts. I still like working with models directly, so I'd go with the DocumentListener. Sadly I don't believe that it has a corresponding abstract. PHP Code:
|
| All times are GMT +1. The time now is 05:29 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.