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??

7 Years
Discussion Span
Last Post by warlord902

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

public static void main(String[] args) {
        JFrame frame = new JFrame("Hello, World!");
        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);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.