重写MouseListener方法,但编译器说不然?

时间:2015-09-28 11:00:36

标签: java override abstract mouselistener

        JTextArea messageDisplayArea=new JTextArea();
        messageDisplayArea.addMouseListener(new MouseListener(){
            public void mouseEntered(MouseEvent m){
                JOptionPane.showMessageDialog(null,"a");
            }
        });
        messageDisplayArea.addMouseListener(new MouseListener(){
            public void mouseExited(MouseEvent m){

            }
        });
        messageDisplayArea.addMouseListener(new MouseListener(){
            public void mouseClicked(MouseEvent m){

            }
        });
        messageDisplayArea.addMouseListener(new MouseListener(){
            public void mousePressed(MouseEvent m){

            }
        });
        messageDisplayArea.addMouseListener(new MouseListener(){
            public void mouseReleased(MouseEvent m){

            }
        });

这是我的代码的一部分,我已经导入了java.awt。*和java.awt.event。*和javax.swing。*但是没有实现MouseListener接口。我已经覆盖了MouseListener接口中的所有方法,但编译器抛出了5个错误,所有这些都表示该类不是抽象的,并且不会覆盖MouseListener中的抽象方法。我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试添加@Override。

使用该代码,您不需要实现MouseListener。

而不是new Mouselistener()使用new MouseAdapter()

示例代码:

    JTextArea textArea = new JTextArea();
    textArea.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
        }
        @Override
        public void mouseReleased(MouseEvent e) {
        }
    });

JTextArea textArea = new JTextArea(); textArea.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } });