Ignoring "Enter Key" in JTextArea

Right now I'm trying to figure out how to make a JTextArea act like I've pressed a "submit" button when I press the Enter key, rather than add a newline character. This code shows the end result I want, except I don't want to have to remove the \n inserted by the enter key.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SSCCE extends JFrame implements KeyListener
     private static JTextArea t = new JTextArea(1,10);
     public SSCCE()
          t.addKeyListener(this);
     @Override
     public void keyPressed(KeyEvent arg0)
     @Override
     public void keyReleased(KeyEvent arg0)
          JTextArea src = (JTextArea) arg0.getSource();
          if(arg0.getKeyChar() == KeyEvent.VK_ENTER)
               String s = src.getText();
               s = s.substring(0, s.length() - 1);
               t.setText(s);
     @Override
     public void keyTyped(KeyEvent arg0)
     public static void main(String args[])
          JFrame f = new JFrame("SSCCE");
          JPanel p = new JPanel();
          new SSCCE();
          p.add(t);
          f.add(p);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setSize(200,100);
          f.setLocationRelativeTo(null);
          f.setVisible(true);
}

Yeah, I figured that out after I posted that. So anyway, here's what I got, and it works, except I extended AbstractAction so I didn't have to use an anonymous class.
package test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
public class SSCCE extends AbstractAction
     private static JTextArea t = new JTextArea(1,10);
     private static JLabel l = new JLabel();
     private static String s = "";
     public SSCCE()
          t.getActionMap().put(t.getInputMap().get(KeyStroke.getKeyStroke("ENTER")), this);
     public void actionPerformed(ActionEvent e)
          s+=t.getText()+"<br/>";
          l.setText("<html>"+s+"</html>");
          t.setText("");
     public static void main(String args[])
          JFrame f = new JFrame("SSCCE");
          JPanel p[] = {new JPanel(),new JPanel()};
          new SSCCE();
          l.setText("<html> </html>");
          p[0].add(l);
          p[1].add(t);
          f.add(p[0],BorderLayout.WEST);
          f.add(p[1],BorderLayout.SOUTH);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setSize(200,200);
          f.setLocationRelativeTo(null);
          f.setVisible(true);
}

Similar Messages

  • How can i disable the Enter key in JTextArea?

    How can i disable the Enter key in JTextArea?
    When i press Enter key in JTextArea,I hope JTextArea do nothing.
    Thanks!

    HI, I've the same problem;
    uncle_alice solution works fine, but if I paste in textArea a multi-line text,
    this last results on more lines (rows);
    Isn't possible to avoid this?
    Alternatively, how can I disable cut/copy/paste on TextArea?
    Thank you in advance.
    MargNat
    Message was edited by:
    MargNat

  • Problem with disabling "ENTER" key in JTextArea

    Hi,
    I have the following codes to disable the 'ENTER' key in the JTextArea,
    but it does not work. Does anyone know why?
    KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    textarea.getKeymap().removeKeyStrokeBinding(enterKey);
    textarea.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
    // do something
    Thanks,
    Pin

    I don't know how you mean "disable", but if you are going to ignore the Enter key, then add a KeyListener to the text area, and in the key pressed method, consume() the key event if the VK_ENTER was pressed. That's all, and you don't have to deal with that key binding thingy.
    The other two event types (typed and released) might be ignored, the enter is processed during key press (as it is now, with the default settings).
    The reason is that processing the Enter key (and other such internally understood keys) is done by the peer, but the peer won't get the key event if it's already consumed.
    FYI: Were it a JTextField, consuming the Enter key presses would mean that the field won't fire action events any more. Since text area does not fire action events, therefore it's a non issue.
    FYI2: Consuming the event only blocks the event to be sent to the peer, all the other listeners still get it.

  • DOWN Traversal out of JTextArea using SHIFT+ENTER key combination.

    Hi folks
    I slightly modified the focus-traversal code presented in Java Tutorial (http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html) to replace the CTRL+TAB combination with SHIFT-ENTER (because it is easier to type) but the code does not work. The code in the tutorial works for just ENTER key only. Am I making any mistake? Can anyone help me on this?
    Thanks in advance.
    Asif

    Thanks for your reply, Srinath. Following is the code (in hyphenated borders):
    =====================================================================
    Set forwardKeys = getFocusTraversalKeys(
    KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
    Set newForwardKeys = new HashSet(forwardKeys);
    newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK));
    setFocusTraversalKeys(KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS,
    newForwardKeys);
    =====================================================================
    Can you help me now? I would really appreciate it. Thanks
    Asif

  • Handling Enter key event in JTable

    Hi...
    This is particularly for the user "VIRAVAN"...
    I have followed your method ,and got results too.. but the
    processKeyBinding(.. method is called 4 times,same problem addressed by you before, but I didn't understood it...
    Please help me...
    Here is my code...
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed)
    System.out.println("Wait");
    if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))
    int selRow = getSelectedRow();
    int rowCount = getRowCount();
    int selCol = getSelectedColumn();
    String val =(String)getValueAt(selRow,selCol);
    boolean b= getCellEditor(selRow,selCol).stopCellEditing();
    System.out.println(b);
    System.out.println(rowCount-1 + " "+ selRow + " " + getSelectedColumn());
    if((!val.equals("")) && selRow==rowCount-1)
    System.out.println(rowCount-1 + " "+ getSelectedRow()+ " " + getSelectedColumn());
    blank1 = new String[columns];
    for(int p=0;p<columns;p++)
    blank1[p]="";
    Diary.this.datarows.addElement(blank1);
    // dataModel.fireTableStructureChanged();
    //dataModel.fireTableDataChanged();
    Diary.this.dataModel.fireTableChanged(null);
    else if(ks ==KeyStroke.getKeyStroke(KeyEvent.VK_1,0))
    System.out.println("One One One One ");
    return super.processKeyBinding(ks,e,condition,pressed);

    It's been a while since I looked at the code, but essentially there are three key event types:
    1) key pressed,
    2) key typed,
    3) key released.
    So I would expect the processKeyBind to see all three of them. However, ks==KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) is true only when a key typed event is detected (the other types can be ignored by passing it up the food chain where they will eventually be consumed). Now...., if I understand you correctly, you want to terminate edit on the present of Enter key, right? Here is how I'd suggest you do:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }Ok.... now, it appears that you want to do something else also... i.e., add a new row to the table if the editing row is the last row and the editing column is the last column of the last row. You can't do that in the same thread (i.e., you must wait until the update in the current thread is completed). So, what you must do is use the SwingUtilities.InvokeLater, like this:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             if (getEditingRow()+1==getRowCount() && getEditingColumn()+1==getColumnCount()) {
                SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
    // put the code for adding new row here
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }OK?
    ;o)
    V.V.
    PS: posted code is untest but should work!

  • Using "Enter Key" on Button launches new window

    I've written a Google Search portlet using the Google API. The user enters a Search Term in a text box and then clicks on a button to begin the search. It works fine as long as the user clicks the button with the mouse. However, I'm finding that many times they just use the enter key thinking its also mapped to the button. The search works, but now displays the results in a new page leaving the portal. How can I get the "Enter Key" to operate the same way as mouse clicking on the button?
    Paul

    Here's what I have in my Page_Load (if you're using aspx) that traps the Enter key. In my case I just ignore it, but you can obviously replace the function body to do whatever you want.
    this.RegisterStartupScript("captureEnterKey", "<script for=document event=onkeydown>if (event.keyCode == 13) {return false;}</script>");

  • Enter key in jato:textField crashes ViewBean

    I have a jato:textField in a very simple JSP/ViewBean which was migrated
    from NetDynamics with the iMT tool and then hand-modified to work under the
    JATO framework.
    If I click Enter in the textField, the page crashes with ServletException
    "The request was not handled by the specified handler". It doesn't give a
    line number. Using an IDE debugger (JBuilder) I see that a forwardTo()
    method has been invoked.
    Other pages don't react to the enter key like this. They beep the
    client. Exactly what I want. Where do I look for trouble?
    Ned Kellogg
    Harvard University Development Office
    124 Mt Auburn Street, 4th Floor
    Cambridge, MA 02138
    617-495-4164
    [Non-text portions of this message have been removed]

    Did you try searching the forum first before posting your questions?
    The following keywords, taken directly from your question would be a good place to start: "disable enter jtextarea".

  • Repeat last command with enter key in dbx

    I am using dbx 7.7 on Solaris 10 (Sun Studio 12.1). Is it possible to configure dbx so that pressing the <enter> key will always repeat the previos command? for instance, if i do one "next" command, i want consequent <enter> key-presses to do "next", until i explicitly execute a different command.
    Thanks,
    Yael

    yaelfrommer wrote:
    Hello Jean,
    Thanks for this advice, i started working with dbxtool and it's very nice.
    2 questions:
    1. The Function keys (F7, F8, etc.) don't work, any idea what could be the problem?There is a bug in the dbx cmdio window where it ignores F-key. It doesn't even have
    a decent context menu. You should be able to get F7 etc working by moving the
    focus elsewhere, like the editor window.
    2. In the default .dbxrc file there's a line "button ignore step up" to "add `step up' button to GUI", but no button was added. Is there anything else i should do to make this work?
    These are really old. (we should remove them from the default .dbxrc!)
    The current way to add a button is via Debug->NewDbxButton
    Thanks,
    Yael

  • Apple, why did you change my Keyboard and remove the enter key?

    Hi all,
    I had my new black MacBook delivered just before Christmas. The keyboard has changed from my previous Black MacBook (the one a colleague poured wine over and killed... grrr).
    Apple have changed the look of the command key and removed the Apple logo (very sad), but more frustratingly have replaced the 'enter' key with another 'option' key.
    I found the 'enter' key really useful, especially for pull down menu and really miss having one.
    Does anyone know if there is a way to assign the new 'option' key to be an 'enter' key?
    Cheers
    Scott.

    I just received a new(refub) MacBook 2.2GHz today and was very disappointed to find the enter key missing. After selling my G4 PowerBook six months ago, I was so looking forward to having the convenience of being able to slap the enter key for dialog boxes with and submitting forms without having to move my hand from the trackpad. I hope that someone will come up with a way to replace the functionality of the missing enter key.
    Which brings me to my next point- There has been a big oversight in the implementation of the MacBook's replacement of the Enter Key, which is to use the FN+Return keys. It seems that when using the FN key with the Return key, the system will ignore the Command key being invoked. I discovered this very quickly. Anyone who uses Apple Remote Desktop knows that in order to send a Unix command to a remote machine, you type the command in the 'send UNIX command' window, then hit Command+Enter to send the command. Return produces a carriage return, FN+Return does nothing, and FNCommandReturn does nothing. The only current work around is to use the track pad to the "Send" button and click, which really slows things down.

  • How to add a listener for enter key

    I'd like to build a chatzone applcation just like msn. The application
    has two textarea, one is for the messages sent and recieve and one is
    for the message typing area. Just like MSN, I'd like to send the text
    after the user pressed enter key. But my problem is I don't know how
    to make a key listener. I've tried jTextArea1.addKeyListener() but I don't
    know how to use it. Anyone can help me?
    Thanks in advance

    KeyListener is just an interface, so you could use:
    public class MyKeyListener implements KeyListener
       private JTextArea area = null;
       public MyKeyListener (JTextArea area)
            this.area = area;
       // Don't care about a key being pressed.
       public void keyPressed (KeyEvent e) {}
       // Don't care about a key being typed.
       public void keyTypes (KeyEvent e) {}
       // We care about the key being released.
       public void keyReleased (KeyEvent e)
           // Check what key it is.  Note sure if \n is the right one...maybe use the key codes.
           if (e.getKeyChar () == '\n')
                // The return key has been pressed and released, they really meant to press it!
                // Get the last line of the text from the text area.  This bits up to you...maybe
                // store the last location of the caret and then read from that point up
                // to the current point...
    }You can also use a DocumentListener if you are using a JTextArea but this is a little bit more complex but may be better, DocumentListeners work on telling you about more macro changes to the document...

  • Lenovo G550 missing Enter key

    Hi,
    I am missing the "Enter" key (part of main keyboard, not part of numeric keypad) on my G550 keyboard. It is not the "horizontal" shape Enter key, but the more "vertical/L-shape" Enter key.
    Can anyone maybe help me to find out where I can get a replacement key?
    Many thanks,
    Ed

    Hello and welcome,
    The Google gives you several options for "lenovo g550 replacement key", including eBay.  Here's one vendor that seems to understand the difference between the two ENTER keys:
    IBM Lenovo G550 Laptop Keys Replacement
    Note: I haven't used this vendor - or any other for this purpose.  Hopefully someone else can chime in with a specific referral.  Until then, this hopefully gives you something to consider.
    Z.
    The large print: please read the Community Participation Rules before posting. Include as much information as possible: model, machine type, operating system, and a descriptive subject line. Do not include personal information: serial number, telephone number, email address, etc.  The fine print: I do not work for, nor do I speak for Lenovo. Unsolicited private messages will be ignored. ... GeezBlog
    English Community   Deutsche Community   Comunidad en Español   Русскоязычное Сообщество

  • How to trap the Escape & Enter key ?

    I want to close the window when user presses escape key & want to trap the enter key for some action.
    Help will be higly appreciated.

    import javax.swing.*;
    public class KeyItIn extends JFrame{
       JTextArea jta[] = new JTextArea[2];
       public KeyItIn() {
          getContentPane().setLayout(new java.awt.GridLayout(2,1) );
          for(int i=0; i<2; i++){
             jta[i] = new JTextArea();
             jta.setBorder(BorderFactory.createEtchedBorder());
    jta[i].addKeyListener(new EventKeyHandler() );
              getContentPane().add(jta[i]);
    setDefaultCloseOperation( EXIT_ON_CLOSE );
    pack();
    class EventKeyHandler extends java.awt.event.KeyAdapter{
    public void keyPressed(java.awt.event.KeyEvent e){     
    jta[0].setText(" Key Typed: "+(char)e.getKeyCode());
    jta[1].setText(" Key code = "+e.getKeyCode() );
    public static void main(String[] args) {
    new KeyItIn().show();

  • Enter key on multiLine InputText

    Is the Enter Key allowed to use to go to the next line to multiLine inputText?

    Hi,
    Yes it's always allowed, however the problem comes when you then try to output it using an outputText, it won't show the line feed as \n is ignored in HTML. You have to use Trinidad's outputDocument component for that.
    Regards,
    ~ Simon

  • How to refresh changed data in a plannable template with the Enter Key

    Hi,
    The situation I face is as follows.
    Integrated Planning is being implemented as a tool for budgeting. The user changes a value in a plannable cell on the portal and wishes to see the new updated data by pressing ENTER. Currently we have provided a REFRESH button so that the user gets the desired result.
    Is it possible to see the updated value by pressing ' ENTER' and if so , whats the way around to do it.
    thanks in advance.
    Jaya

    Hey guys,
    I'm interested too in this solution. In BPS there is an additional function described in the HowTo Paper HowTo run planning functions on save and other events
    Now I'm looking for this possibility in IP as well in excel-based IP and web-based IP. For example a copy function should be executed automatically when pushing the enter key.
    Thanks a lot!
    Clemens

  • Table Control[Accept Input Only] - "ENTER" Key

    Hi Folks,
    I'm reviving this unanswered thread in relation to table control: when the user press enter, all the values entered disappear.
    [url]Re: Table control (Enter key)[url]
    I have a table control that accepts "ONLY" input, meaning to say, there will be no pre-loading of data in the PBO, so it will loop through the table control itself instead of looping from an internal table.
    Issue: Whenever I press "ENTER" in any column/row of my table control, ALL the values I entered disappear.
    PBO:
    PROCESS BEFORE OUTPUT.
      MODULE CLEAR_OKCODE.
      MODULE LOAD_TABLECTRL.
      LOOP WITH CONTROL TC_DATA.
        MODULE READ_DATA.
      ENDLOOP.
    module READ_DATA output.
      READ TABLE T_DATA INTO WA_DATA INDEX TC_DATA-current_line.
      data : line_count type i.
      "to increase the number of lines in table control dynamically
      describe TABLE t_data lines line_count.
      TC_DATA-lines = line_count + 10.
    endmodule. 
    PAI:
    PROCESS AFTER INPUT.
      LOOP WITH CONTROL TC_DATA.
        MODULE MODIFY_DATA.
      ENDLOOP.
    module MODIFY_DATA input.
    WHEN 'CREATE'.
      "subroutines are here, etc.
    WHEN 'DELETE'.
    WHEN 'BACK'.
      LEAVE TO SCREEN 0.
    endmodule.
    In my ABAP Debug, the value of SY-UCOMM is BLANK whenever I press Enter.
    Thanks.

    Hi
    Your code seems to be rght only the MODIFY statament is useless:
    module READ_DATA output.
      READ TABLE T_ID_CHECK INTO WA_ID_CHECK INDEX TC_ID-current_line.
      IF SY-SUBRC EQ 0.
        ZQID_CHECK-WERKS = WA_ID_CHECK-WERKS.
        ZQID_CHECK-MATNR = WA_ID_CHECK-MATNR.
        ZQID_CHECK-LICHA = WA_ID_CHECK-LICHA.
        ZQID_CHECK-LIFNR = WA_ID_CHECK-LIFNR.
      ELSE.
        CLEAR ZQID_CHECK.
      ENDIF.
    endmodule.
    Now before LOOP of PBO try to set the lines of table control to be display, I've created this report on my system and it works fine:
    .CONTROLS T_CTRL TYPE TABLEVIEW USING SCREEN 100.
    DATA: BEGIN OF ITAB OCCURS 0,
              WERKS LIKE MARC-WERKS,
              MATNR LIKE MARC-MATNR,
              LIFNR LIKE LFA1-LIFNR,
          END   OF ITAB.
    DATA: WA LIKE ITAB.
    START-OF-SELECTION.
      DO 4 TIMES.
        ITAB-WERKS = '5010'.
        ITAB-MATNR = '1234567890'.
        ITAB-LIFNR = '0000000001'.
        APPEND ITAB.
      ENDDO.
      CALL SCREEN 100.
    PROCESS BEFORE OUTPUT.
      MODULE SET_T_CTRL.
      LOOP WITH CONTROL T_CTRL.
        MODULE READ_DATA.
      ENDLOOP.
    PROCESS AFTER INPUT.
      LOOP WITH CONTROL T_CTRL.
        MODULE MODIFY_DATA.
      ENDLOOP.
    MODULE SET_T_CTRL OUTPUT.
      DESCRIBE TABLE ITAB LINES T_CTRL-LINES.
    ENDMODULE.                 " SET_T_CTRL  OUTPUT 
    MODULE READ_DATA OUTPUT.
      READ TABLE ITAB INDEX T_CTRL-CURRENT_LINE.
      IF SY-SUBRC = 0.
        MOVE-CORRESPONDING ITAB TO WA.
      ELSE.
        CLEAR WA.
      ENDIF.
    ENDMODULE.                 " READ_DATA  OUTPUT
    MODULE MODIFY_DATA INPUT.
      MODIFY ITAB FROM WA INDEX T_CTRL-CURRENT_LINE.
      IF SY-SUBRC NE 0.
        CHECK NOT WA IS INITIAL.
        APPEND WA TO ITAB.
      ENDIF.
    ENDMODULE.                 " MODIFY_DATA  INPUT

Maybe you are looking for