我有以下内容:
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
}
}
}
为什么当我点击左箭头时框架没有变红?我也有它没有键码测试认为无论键它都可以工作,但它没有。谢谢你。