Andrew Lalis
Andrew Lalis

Reputation: 974

Java Swing How to reset JTextArea

I am making a program where the user can type a string message into a JTextArea component, and press enter so that the message is sent, and then the JTextArea should be cleared and the caret position reset to 0.

    JTextArea userChatBox = new JTextArea();
    userChatBox.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==10){
            //If key pressed is enter.  
                client.send(userChatBox.getText());
                userChatBox.setCaretPosition(0);
                userChatBox.setText("");

            }

        }
    });
    userChatBox.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
    userChatBox.setTabSize(4);
    userChatBox.setLineWrap(true);
    userChatBox.setForeground(UIManager.getColor("ColorChooser.foreground"));
    userChatBox.setFont(new Font("DejaVu Serif", Font.PLAIN, 12));
    userChatBox.setBackground(Color.WHITE);
    userChatBox.setBounds(10, 255, 400, 80);
    frmChatClient.getContentPane().add(userChatBox);

However, when the user presses enter, the JTextArea registers this as a return and enters a new line. Even after userChatBox.setCaretPosition(0);, the caret appears on the second line, and subsequently any string sent from the JTextArea will include a blank line. I have also tried setting the selection start and end with no avail.

Upvotes: 1

Views: 713

Answers (1)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9900

as @luxxminer said problem is event occurs first before text append to jtextarea.if you can consume event ,then new line will not append.

so you can use event.consume(); method

if (e.getKeyCode()==10){

    //If key pressed is enter.  
        client.send(userChatBox.getText());
        userChatBox.setCaretPosition(0);
        userChatBox.setText("");
        e.consume();
}

Upvotes: 4

Related Questions