所有组件的KeyListener?

时间:2017-11-14 17:57:27

标签: java swing keylistener

快速简单的问题:我有一个带JButtons的JPanel。我已将ActionListeners附加到按钮,并将KeyListener附加到面板。即使我尝试将焦点放在面板上,按键也没有响应。

所以我试验了KeyListener并将其附加到按钮上,恢复了正常操作。

这是Java的设计,将KeyListener附加到每个组件,还是我错过了一些基本的东西?

快速示例程序,Escape退出,按钮点击交换按钮文本。

// imports from javax.swing
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

// imports from java.awt.event
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class Example implements ActionListener, KeyListener {

    // Frame variables
    private JFrame frame = new JFrame ();
    private JPanel mainPanel = new JPanel ();

    // Buttons
    private JButton thisButton = new JButton ("this"),
        thatButton = new JButton ("that");

    public static void main (String [] args) {

        new Example ();
    }

    public Example () {

        mainPanel.add (thisButton);
        mainPanel.add (thatButton);

        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.add (mainPanel);
        frame.pack ();
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);

        // addition of Listeners
        frame.addKeyListener (this);
        thisButton.addActionListener (this);
        thatButton.addActionListener (this);
        thisButton.addKeyListener (this);
        thatButton.addKeyListener (this);

        frame.requestFocus ();
    }

// ActionListener override
    @Override
    public void actionPerformed (ActionEvent e) {
        String holdString;

        holdString = thisButton.getText ();
        thisButton.setText (thatButton.getText ());
        thatButton.setText (holdString);
    }

// KeyListener overrides
    @Override
    public void keyPressed (KeyEvent e) {}

    @Override
    public void keyReleased (KeyEvent e) {}

    @Override
    public void keyTyped (KeyEvent e) {

            if (e.getKeyChar () == KeyEvent.VK_ESCAPE) {
                System.exit (0);
            }
    }

}

0 个答案:

没有答案