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

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

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.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);
    }

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.