Recognizing enter on text entry

I’m trying to create a simple text adventure and some modules to go along with it. The main window of the engine has a JTextArea for displaying text, a JTextField for entering text, and a JButton to act as a send button.

Right now, the only way I know of to see if enter is pressed while the user is typing in text is to scan each key as its typed to see if it’s enter or not. Is there a better way to recognize when the user hits enter when typing in a JTextField?

sure… you can install KeyListener on that component (JTextField). Basicly you can install KeyListener on every component. See addKeyListener(). When you install it you test key code for VK_ENTER.

ActionListener. An ActionEvent is triggered if the user presses return inside some JTextField.

ok thread hyjack I knew some off the unwritten standards of feel of components was inplemented such as this one, has someone seen the property select-all-on-focus or must I fill in an rfc?

FocusListener?

? … maybe action on parent container?

but I use KeyListener:


        chat_tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent evt) {
                int keyCode = evt.getKeyCode();
                if (keyCode == KeyEvent.VK_ENTER) {
                    JTextField src = (JTextField)evt.getSource();
                    HostedGameData.getMyPlayer().say(src.getText().trim(), 5000);
                    src.setText("");
                    viktorije.requestFocus();
                }
            }
        });

would be nice if it worked. however if you take a JFormattedTextfield the focusevent is triggered before the check on the format which causes the text to become unselected. I have to dig up some code.

there was a bug report about this where the proposed workaround was to use invokelater useing some ugly que-ed thing. now hacking around a normal JFormattedTextfield wasn’t the problem however since JFormattedTextfield is used in quite some compound-components things get really messy.

but I use KeyListener

Sure works. Like you can write x=x+4-3 instead of ++x.

so actionListener is standard, tnx, I’ll change to that

Thanks for all of the replies, and especially thanks to oNyx and Kova for their suggestions. I’ve gone with using ActionListener, and it works great. Thanks again :).