JTextArea new line on shift + enter

后端 未结 3 1695
南笙
南笙 2021-02-08 23:31

I\'ve added a keylistener to my JTextArea field, but it doesn\'t behave as I expected.

inputTextArea.addKeyListener(new KeyAdapter() {
public void keyPressed(Key         


        
相关标签:
3条回答
  • 2021-02-08 23:45

    You may use the InputMap and ActionMap of the JTextArea to map the key strokes to actions:

    private static final String TEXT_SUBMIT = "text-submit";
    private static final String INSERT_BREAK = "insert-break";
    ...
    private void initialize() {
        InputMap input = inputTextArea.getInputMap();
        KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
        KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
        input.put(shiftEnter, INSERT_BREAK);  // input.get(enter)) = "insert-break"
        input.put(enter, TEXT_SUBMIT);
    
        ActionMap actions = inputTextArea.getActionMap();
        actions.put(TEXT_SUBMIT, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                submitText();
            }
        });
    }
    ...
    private void submitText() {
        // TODO
    }  
    

    The original action for ENTER - "insert-break" - is used for shift ENTER.

    0 讨论(0)
  • 2021-02-08 23:51

    Try using keyTyped and not keyPressed. I beleive keyPressed gives you an event for the shift and for the enter, whereas keyTyped gives you one combined event with a modifier.

    0 讨论(0)
  • 2021-02-09 00:01

    Instead of doing the actions immediately on receiving the event, sequence them for later by posting them using SwingUtilities.invokeLater(). The code should look like:

    if(k.isShiftDown()) {
       SwingUtilities.invokeLater(new Runnable() {
          public void run() {
             inputTextArea.append(" \n");
          }
       });
    } else {
       SwingUtilities.invokeLater(new Runnable() {
          public void run() {
              //rest of the else body here
          }
       });
    
    }
    

    In my opinion, the problems seen here are because application-defined actions and internal actions are not being properly sequenced, leading to repaints happening before the text has been modified.

    0 讨论(0)
提交回复
热议问题