views:

43

answers:

3

Hi

I have a text area that I would like to become blank when the enter button is pressed. I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?

thanks

A: 

Hi

I have a text area that I would like to become blank when the enter button is pressed.

This, I understand. Here's how you can do that:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main {
    public static void main(String[]args) {
        final JFrame frame = new JFrame();
        final JTextArea area = new JTextArea();
        area.setPreferredSize(new Dimension(200, 200));
        area.addKeyListener(new KeyAdapter(){
            @Override
            public void keyReleased(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    area.setText("");
                }
            }
        });
        frame.add(area);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?

That, I don't understand.

Bart Kiers
+2  A: 

Are you listening for the ENTER key on the text area and then clearing it? The following works for me:

final JTextArea ta = new JTextArea();
ta.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
            ta.setText("");
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }
});
dogbane
A: 

The problem is probably that you are not consuming the keystroke event, and although the text area is cleared, the normal processing of the keystroke ends up inserting a newline.

Rather than trapping the keystroke event (which isn't necessarily portable) I would recommend using a DocumentFilter. There is a tutorial here that shows you how to write one. Implement the filter so that when there is a 'newline' in the insert or replace string, replace the entire contents of the document with "".

However this approach can't tell the difference between a newline typed at the keyboard and one pasted into the text area.

DJClayworth