1

我正在学习 java,在做 MouseListener 问题时,我在类声明中遇到错误,尝试了我所知道的一切,请帮助我。根据我的说法,我已经正确完成了所有编码,也将代码粘贴到了 IDE 中,但出现了同样的错误。

谢谢

     import java.awt.*;
     import java.awt.event.*;
     import javax.swing.*;

       public class Sub extends JFrame      
    {
private JPanel mousepanel;
private JLabel statusbar;

public Sub()
{
    super("Mouse Events");
    // we didnt have a FlowLayout as we had in previous programs

    mousepanel = new JPanel();
    mousepanel.setBackground(Color.WHITE);
    add(mousepanel, BorderLayout.CENTER); //BorderLayout used instead of FlowLayout and it will place it in the center of the window.

    statusbar = new JLabel("Default");
    add(statusbar, BorderLayout.SOUTH); // same as above

    thehandler handler = new thehandler();
    mousepanel.addMouseListener(handler);
    mousepanel.addMouseMotionListener(handler);

            private class thehandler implements MouseListener, MouseMotionListener
    {
        public void mouseClicked(MouseEvent event)
        {
            statusbar.setText(String.format("Clicked at %d, %d", event.getX(), event.getY()));
        }
        public void mousePressed(MouseEvent event)
        {
            statusbar.setText("You press down the mouse.");
        }
        public void mouseReleased(MouseEvent event)
        {
            statusbar.setText("You released the mouse.");
        }
        public void mouseEntered(MouseEvent event)
        {
            statusbar.setText("You enetered the mouse panel area.");
            mousepanel.setBackground(Color.PINK);
        }
        public void mouseExited(MouseEvent event)
        {
            statusbar.setText("The mouse has left the window.");
            mousepanel.setBackground(Color.WHITE);
        }

        //these aremouse motion events

        public void mouseDragged(MouseEvent event)
        {
            statusbar.setText("Your are dragging the mouse.");
        }
        public void mouseMoved(MouseEvent event)
        {
            statusbar.setText("You moded the mouse.");
        }
    }
}
  }
4

3 回答 3

1

您需要将thehandler类定义移出Sub构造函数的范围。

旁注:类名以大写字母开头。

于 2012-12-12T21:16:11.290 回答
0

将您的类定义移到构造函数之外,如下所示:

public Sub() {
    // ... rest of code
}

// ... rest of code

private class thehandler implements MouseListener, MouseMotionListener {
    // ... rest of code
}
于 2012-12-12T21:18:04.787 回答
0

检查您的大括号并使用一些 IDE,它将帮助您更轻松地纠正错误。

于 2012-12-18T17:50:46.083 回答