Java JTextArea KeyListener

跟風遠走 提交于 2020-02-27 06:19:06

问题


When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else. How should I do that?

textarea.addKeyListener(new KeyListener(){
    @Override
    public void keyPressed(KeyEvent e){
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
        button.doClick();
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
});

回答1:


Use .consume():

Consumes this event so that it will not be processed in the default manner by the source which originated it.

public void keyPressed(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
    e.consume();
    button.doClick();
    }
}

Documentation




回答2:


You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)

A small program for your help :

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

public class KeyBindingExample {

    private static final String key = "ENTER";
    private KeyStroke keyStroke;

    private JButton button;
    private JTextArea textArea;

    private Action wrapper = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            button.doClick();
        }
    };

    private void displayGUI() {
        JFrame frame = new JFrame("Key Binding Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel(new BorderLayout(5, 5));

        textArea = new JTextArea(10, 10);
        keyStroke = KeyStroke.getKeyStroke(key);
        Object actionKey = textArea.getInputMap(
                JComponent.WHEN_FOCUSED).get(keyStroke);
        textArea.getActionMap().put(actionKey, wrapper);

        button = new JButton("Click Me!");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.out.format("Button Clicked :-)%n");
            }
        });     

        contentPane.add(textArea, BorderLayout.CENTER);
        contentPane.add(button, BorderLayout.PAGE_END);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new KeyBindingExample().displayGUI();
            }
        };
        EventQueue.invokeLater(r);
    }
}


来源:https://stackoverflow.com/questions/18483813/java-jtextarea-keylistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!