Jpanel想要监听到键盘事件,必须先要获取焦点
this.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyChar()==KeyEvent.VK_1){
zwcpanel.setVisible(true);
packType = "1";
try {
musicUrl = new URL("file:"
+ rootPath
+ "/swing/voice/please_swipe.au"); //音乐URL
ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (Exception ee) {
ee.printStackTrace();
}
}
if(e.getKeyChar()==KeyEvent.VK_2){
// packButton2.doClick();
zwcpanel.setVisible(true);
packType = "2";
try {
musicUrl = new URL("file:"
+ rootPath
+ "/swing/voice/please_swipe.au"); //音乐URL
ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (Exception ee) {
ee.printStackTrace();
}
}
if(e.getKeyChar()==KeyEvent.VK_3){
// packButton3.doClick();
zwcpanel.setVisible(true);
packType = "3";
try {
musicUrl = new URL("file:"
+ rootPath
+ "/swing/voice/please_swipe.au"); //音乐URL
ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (Exception ee) {
ee.printStackTrace();
}
}
if(e.getKeyChar()==KeyEvent.VK_4){
// packButton4.doClick();
zwcpanel.setVisible(true);
packType = "4";
try {
musicUrl = new URL("file:"
+ rootPath
+ "/swing/voice/please_swipe.au"); //音乐URL
ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
});
private static void createAndShowGUI() {
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JPanel test = new Test();
frame.getContentPane().add(test);
frame.setVisible(true);
test.requestFocus(); // 注意,与上面的这一句不能反