最近,我一直在学习Java,并且不断遇到以下错误:this method (*) is undefined for the type(*)。我过去通过导入缺少的库来解决它,但是在下面的代码中,即使导入很多库也无济于事。

由于以下两行而出现此错误:

     mousepanel.addMouselistener(handler)

            mousepanel.addMouseMotionlistener(handler)


我正在尝试创建一个窗口来测试mouselistenermousemotionlistenser

这是我的代码:

    public class Gui extends JFrame{
        private JPanel mousepanel;
        private JLabel statusbar ;
        //Gui
        public Gui() {
            super("the title");

            mousepanel =new JPanel();
            mousepanel.setBackground(Color.WHITE);
            add(mousepanel,BorderLayout.CENTER);

            statusbar = new JLabel("default");
            add(statusbar,BorderLayout.SOUTH);

          HandlerClass   handler = new HandlerClass();
            mousepanel.addMouselistener(handler);
            mousepanel.addMouseMotionlistener(handler);


        }
        private class  HandlerClass implements Mouselistener ,MouseMotionlistener {
            //functions
            public void mouseClicked (MouseEvent e)
            {
                statusbar.setText("click");
            }public void mousePressed (MouseEvent e)
            {
                statusbar.setText("press");
            }public void mouseReleased (MouseEvent e)
            {
                statusbar.setText("release");
            }public void mouseEntered (MouseEvent e)
            {
                statusbar.setText("enter");
                mousepanel.setBackground(Color.RED);
            }public void mouseExited (MouseEvent e)
            {
                statusbar.setText("out");
                mousepanel.setBackground(Color.WHITE);
            }
            //functions
            public void mouseDragged (MouseEvent e)
            {
                statusbar.setText("drag");
            }
            public void mouseMoved (MouseEvent e)
            {
                statusbar.setText("move");
            }




    }

}

最佳答案

您的方法名称不正确。您需要camelCase方法名称。例如,使用addMouseListener(handler)代替addMouselistener(handler)

注意:您应该使用IDE来检查编译时错误。

07-24 09:16