首页上一页 1 下一页尾页 2 条记录 1/1页
第13章 Swing 程序设计 求大神指导如何使一个类实现多种类型的事件监听
发表在Java图书答疑
2016-03-18
是否精华
是
否
版块置顶:
是
否
问题详述:我在MyPanel类里同时实现了ActionListener和KeyListener,但是我只要释放掉注释的代码,键盘监听就会失效,请问这种问题的错误原因是什么,应该怎么解决?
源码如下:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args){
new MyFrame();
}
}
class MyFrame extends JFrame{
MyPanel mp=null;
public MyFrame(){
mp=new MyPanel();
this.addKeyListener(mp);
this.add(mp);
this.setVisible(true);
this.setLocation(500, 300);
this.setSize(150, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements ActionListener,KeyListener{
JButton jb=null;
public MyPanel(){
jb=new JButton("监听测试");
jb.setActionCommand("test");
jb.addActionListener(this);
// this.add(jb);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("test")){
System.out.println("按钮被点击");
}
}
public void keyTyped(KeyEvent e){
System.out.println("键盘键入某键");
}
public void keyReleased(KeyEvent e){
System.out.println("键盘释放某键");
}
public void keyPressed(KeyEvent e){
System.out.println("键盘按下某键");
}
}
源码如下:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args){
new MyFrame();
}
}
class MyFrame extends JFrame{
MyPanel mp=null;
public MyFrame(){
mp=new MyPanel();
this.addKeyListener(mp);
this.add(mp);
this.setVisible(true);
this.setLocation(500, 300);
this.setSize(150, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements ActionListener,KeyListener{
JButton jb=null;
public MyPanel(){
jb=new JButton("监听测试");
jb.setActionCommand("test");
jb.addActionListener(this);
// this.add(jb);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("test")){
System.out.println("按钮被点击");
}
}
public void keyTyped(KeyEvent e){
System.out.println("键盘键入某键");
}
public void keyReleased(KeyEvent e){
System.out.println("键盘释放某键");
}
public void keyPressed(KeyEvent e){
System.out.println("键盘按下某键");
}
}