0

I Know this has been asked before, but everywhere I see the question the answer isn't helpful at all... so here goes.

I using the book Learning Java and there's an example that looks like this:

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) {

    }
}

I typed it into the editor, but it gives me the error:

HelloJava2.java:15: error: HelloComponent2 is not abstract and does not override abstract method mouseDragged(MouseEvent) in MouseMotionListener class HelloComponent2 extends JComponent ^ 1 error

I am completely new to this language so I am completely lost on what implementing even means... any help is greatly appreciated!

1 Answers1

1

The problem is you forgot implement a method called mouseDragged(MouseEvent) of the interface MouseMotionListener. So you only need include the method, something like this:

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) {

  }
}
JTejedor
  • 1,082
  • 10
  • 24
  • thank you for answering, it ended up being something very stupid... I put the arguments in paintComponent that should have been in the non-existent mouseDragged; (MouseEvent e) instead of (Graphics g)... I must have skipped it while copying... I also didnt need the @Override, not sure what it does either – Agustin Fitipaldi Dec 07 '17 at 00:10
  • You are welcome @AgustinFitipaldi. Override annotation is recommended, the reasons are explained in this [question](https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why) – JTejedor Dec 07 '17 at 07:55