Mousedragged未获得认可

时间:2013-06-01 20:08:59

标签: java swing focus jpanel mousemotionevent

有人可以告诉我为什么mousedragged在以下代码中无法识别,并且可能帮助我解决这个问题吗?

public class Hello extends JPanel implements KeyListener, MouseListener, MouseMotionListener{
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    public Hello() {
        addKeyListener(this);
        addMouseListener(this);
        addMouseMotionListener(this);
        panel.addKeyListener(this);
        panel.addMouseListener(this);
        frame.addKeyListener(this);
        frame.addMouseListener(this);
    }

    public static void main(String [] args){
        Hello play = new Hello();
        play.setPanel();
    }
    public void setPanel(){
        panel.setLayout(null);
        frame.add(panel);
        frame.setLayout(null);
        panel.setBounds(0,0,100,100);
        frame.setVisible(true);
        panel.setVisible(true);
        panel.setFocusable(true);
        frame.setSize(100,100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void keyTyped(KeyEvent arg0){
        System.out.println("keytyped");
    }
    public void keyPressed(KeyEvent arg0){
        System.out.print("keypressed");
    }
    public void keyReleased(KeyEvent arg0){
        System.out.println("keyreleased");
    }
    public void mousePressed(MouseEvent arg0){
        System.out.println("mousepressed");
    }
    public void mouseReleased(MouseEvent arg0){
        System.out.println("mousereleased");
    }
    public void mouseClicked(MouseEvent arg0){
        System.out.println("mouseclicked");
    }
    public void mouseEntered(MouseEvent arg0){
        System.out.println("mousenentered");
    }
    public void mouseExited(MouseEvent arg0){
        System.out.println("mouseexited");
    }
    public void mouseDragged(MouseEvent arg0){
        System.out.println("mousedragged");
    }

2 个答案:

答案 0 :(得分:0)

面板具有焦点,因此您需要将MouseMotionListener添加到面板中。

答案 1 :(得分:0)

您将MouseMotionListener设置为类'面板,但该面板不在焦点上。

    panel.addKeyListener(this);
    panel.addMouseListener(this);
    frame.addKeyListener(this);
    frame.addMouseListener(this);

在这里,您为帧和面板提供了键和鼠标侦听器。然后在代码中进一步向下,将框架和面板设置为可见。留下MouseMOTIONListener的唯一面板是隐形结构面板。

    panel.addKeyListener(this);
    panel.addMouseListener(this);
    panel.addMouseMotionListener(this);
    frame.addKeyListener(this);
    frame.addMouseListener(this);
    frame.addMouseMotionListener(this);

给它一个镜头,看看它在哪里。我很长一段时间没有参加过挥杆练习,但我认为这可能有所帮助。