7

当我按下 ENTER 时,我的 JTextArea 开始一个新行,我只想对 doClick() 方法执行其他操作。我该怎么做?

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) {
    }
});
4

2 回答 2

10

使用.consume()

使用此事件,以便它不会由发起它的源以默认方式处理。

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

文档

于 2013-08-28T09:18:55.427 回答
8

您应该使用任何有问题的KeyBindings 。从他的角度来看,水平太低了。您正在使用与 相关的概念,用于以更高的效率执行相同的任务并提供所需的结果:-)JTextComponentKeyListenersSwingAWTSwingKeyBindings

一个小程序为您提供帮助:

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);
    }
}
于 2013-08-28T14:31:00.590 回答