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.
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.
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:
public static void main(String[] argv) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame jf = new JFrame(); Document d = new PlainDocument(); JTextField jf1 = new JTextField(); JTextField jf2 = new JTextField();
Something like that to see what I mean. You should find everything you need in java.awt, javax.swing and javax.swing.text. If it works as I expect, you'll have two fields, the bottom one disabled and as you type in the text area it automatically fills in the second.
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.
public static void main(String[] argv) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame jf = new JFrame(); final SharedDocumentTest t = new SharedDocumentTest();
JTextField jf1 = new JTextField(); JButton jb = new JButton("Shows it."); jb.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, t.getString()); } });