使用mousemovementListener实现错误

时间:2017-12-06 19:49:22

标签: java

我知道以前曾经问过这个问题,但无论在哪里,我都会看到答案根本没有帮助......所以这里就是这样。

我使用“学习Java”一书,有一个看起来像这样的例子:

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

public class HelloJava2 {
    public static void main( String [] args ) {
        JFrame frame = new JFrame( "HelloJava2" );
        frame.add( new HelloComponent2("Hello, Java!") );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize( 300, 300 );
        frame.setVisible( true ); 
    }
}

class HelloComponent2 extends JComponent
    implements MouseMotionListener 
{
    String theMessage;
    int messageX = 125;
    int messageY = 95;

    public HelloComponent2( String message ) {
        theMessage = message;
        addMouseMotionListener(this);
    }

    public void paintComponent(MouseEvent e) {
        // Save the mouse coordinates and paint the message.
        messageX = e.getX();

        messageY = e.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {

    }
}

我将它输入编辑器,但它给了我错误:

HelloJava2.java:15:错误:HelloComponent2不是抽象的,并且不会覆盖MouseMotionListener中的抽象方法mouseDragged(MouseEvent) class HelloComponent2扩展了JComponent ^ 1错误

我对这种语言完全陌生,所以我完全迷失了甚至意味着什么......任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

问题是你忘了实现一个名为mouseDragged(MouseEvent)的接口MouseMotionListener的方法。所以你只需要包含这样的方法:

class HelloComponent2 extends JComponent
    implements MouseMotionListener
{
  String theMessage;
  int messageX = 125;
  int messageY = 95;

  public HelloComponent2( String message ) {
    theMessage = message;
    addMouseMotionListener(this);
  }

  public void paintComponent(MouseEvent e) {
    // Save the mouse coordinates and paint the message.
    messageX = e.getX();

    messageY = e.getY();
    repaint();
  }
  //Here it is the method you forgot include in your class
  @Override
  public void mouseDragged(MouseEvent e) {

  }

  public void mouseMoved(MouseEvent e) {

  }
}