1

我有以下内容:

import javax.swing.JFrame;

public class Directions {

    public Directions(){
        JFrame frame = new JFrame("Direction");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DirectionPanel());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Directions myTest = new Directions();
    }
}

第二类:

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

public class DirectionPanel extends JPanel{
    public DirectionPanel(){
        addKeyListener(new DirectionListener());
        setBackground(Color.yellow);
    }

    private class DirectionListener implements KeyListener{

        @Override
        public void keyPressed(KeyEvent e) {
            //JOptionPane.showMessageDialog(null, "Hello Johnny");
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT){
                setBackground(Color.red);
            }
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
        }
    }
}

为什么当我点击左箭头时框架没有变红?我也有它没有键码测试认为无论键它都可以工作,但它没有。谢谢你。

4

2 回答 2

6
public DirectionPanel(){
   addKeyListener(new DirectionListener());
   setFocusable(true);// INSERT THIS
   setBackground(Color.yellow);
}

JPanel需要可聚焦以接收 KeyEvents

于 2010-02-05T18:22:00.773 回答
3

当使用键盘时, Swing 组件应该使用Key Bindings(而不是 KeyListeners)来调用 Action。这样做的一个附带好处是您不必担心可聚焦性。

Action left = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println( "Left" );
    }
};

Object key1 = "left";
KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks1, key1);
panel.getActionMap().put(key1, left);
于 2010-02-05T18:27:37.970 回答