954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Stop Cursor From Moving to next row when enter is pressed

So my problem is that, i have a text area with 3 rows. Its a part of a chat application which receives text from a user.

I want to send the text and clear the text area as soon as the user presses the enter key. Now the problem is that whenever user presses the enter key the cursor goes to next line(row) and then on clearing the text area it comes to first, so it looks weird to a user that the cursor goes to next line and then comes to first.

So I want to stop the cursor from going into the next line on press of enter key, i had used key events but found of no use, anyone have suggestions for this??

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 

On a key pressed event, test for and remove the newline character.

seanbp
Junior Poster
129 posts since Jul 2010
Reputation Points: 20
Solved Threads: 15
 

I had failed to remove the new line character may be, the problem is still the same.
Can you please help me with a code snippet may be I am not doing that properly

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 
public static void main(String[] args) {
        JFrame frame = new JFrame("Hello, World!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 250);
        frame.setLayout(new BorderLayout());
        JTextArea text = new JTextArea();
        text.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
                
            }

            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == e.VK_ENTER) e.consume();
            }

            public void keyReleased(KeyEvent e) {

            }

        });
        JScrollPane scroller = new JScrollPane(text);
        frame.add(scroller, BorderLayout.CENTER);
        frame.setVisible(true);
    }
seanbp
Junior Poster
129 posts since Jul 2010
Reputation Points: 20
Solved Threads: 15
 

Oh thanks a lot, i was missing the consume function.

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: