Skip to main content
gamedev.net
🔒 Locked

[java] Mouse Position

Started by NightMonkey Aug 31, 2003 at 7:20 AM 3 replies 600+ views
Original Post
NightMonkey
NightMonkey
Hi, im new to Java and am trying to create a simple applet that displays the coordinates of the mouse pointer when the button is pressed. The code for it is as follows: import java.awt.*; import java.awt.event.*; import java.awt.event.MouseListener; public class Main extends javax.swing.JApplet implements MouseListener { int xpos,ypos; public void init() { } public void paint(Graphics screen) { screen.drawString("X: "+xpos+" Y: "+ypos,100,100); } public void mousePressed(MouseEvent e) { xpos = e.getX(); ypos = e.getY(); repaint(); } public void start() { repaint(); } } However when i try to compile it I get the following error: "Main is not abstract and does not override abstract method mouseReleased(java.awt.event.MouseEvent)" Does anyone know why this is not working. Any advice would be appriecated.
ManiacMac
ManiacMac
Simple little problem really. When you use "implements MouseListener", then you need to have:

public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mousePresssed(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

Else it will give you that error. That should fix it,

[edited by - ManiacMac on August 31, 2003 9:47:49 AM]
NightMonkey
NightMonkey
Thanks, that got it running but it is still not calling the mouse pressed function when I click the mouse button. Any suggestions?
MadLep
MadLep
To track the motion of a mouse, you need to implement MouseMotionListener rather than plain old MouseListener.

Specifically, add

void mouseMoved(MouseEvent e)
{
xpos = e.getX();
ypos = e.getY();
repaint();
}

void mouseDragged(MouseEvent e) {}

and then get rid of the mousePressed() method. MouseListener listens for higher level mouse events, such as moving over components etc.

Whenever you specify that your class implements an interface, you need to provide implementations for all methods specified by the interface, or declare the class abstract, and have it''s subclasses implement them.
"I pretend to work, they pretend to pay me."

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.