Mouse.java
Posted in Text, on September 2, 2010 at 07:06
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class Mouse implements MouseListener, MouseMotionListener
{
enum MouseState
{
RELEASED,
PRESSED,
ONCE
}
private static final int BUTTON_COUNT = 3;
private Image cursor;
private Component component;
private Point center;
private Point mousePos = null;
private Point currentPos = null;
private boolean[] state = null;
private MouseState[] poll = null;
public Mouse(Component comp)
{
String imgFileName = "mouse.png";
URL url = Mouse.class.getResource(imgFileName);
Image imgc = null;
try
{
imgc=ImageIO.read(url);
}
catch(Exception e)
{
}
this.cursor = imgc;
this.component = comp;
int w = comp.getBounds().width;
int h = comp.getBounds().height;
this.center = new Point(w/2, h/2);
this.mousePos = center;
this.currentPos = center;
this.state = new boolean[BUTTON_COUNT];
this.poll = new MouseState[BUTTON_COUNT];
for(int i=0;i<BUTTON_COUNT;i++)
{
this.state[i] = false;
this.poll[i] = MouseState.RELEASED;
}
disableCursor();
}
public Image getCursor()
{
return this.cursor;
}
public Point getPosition()
{
return this.mousePos;
}
private void disableCursor()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = tk.createImage("");
Point p = new Point(0, 0);
String name = "asdf";
Cursor cur = tk.createCustomCursor(img, p, name);
this.component.setCursor(cur);
}
public synchronized void poll()
{
mousePos = currentPos;
for(int i=0;i<BUTTON_COUNT;i++)
{
if(state[i])
{
if(poll[i]==MouseState.ONCE)
poll[i]=MouseState.PRESSED;
else if(poll[i]==MouseState.RELEASED)
poll[i]=MouseState.ONCE;
}
else
poll[i] = MouseState.RELEASED;
}
}
public boolean isButtonDownOnce(int button)
{
return poll[button-1]==MouseState.ONCE;
}
public boolean isButtonDown(int button)
{
return poll[button-1]==MouseState.PRESSED||
poll[button-1]==MouseState.ONCE;
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
state[e.getButton()-1]=true;
}
public void mouseReleased(MouseEvent e)
{
state[e.getButton()-1]=false;
}
public void mouseEntered(MouseEvent e)
{
mouseMoved(e);
}
public void mouseExited(MouseEvent e)
{
mouseMoved(e);
}
public void mouseDragged(MouseEvent e)
{
mouseMoved(e);
}
public void mouseMoved(MouseEvent e)
{
currentPos = e.getPoint();
}
}
Share this code
Use the link below to share the code:
http://www.codesend.com/view/5f9903cf5257627ee1801b4fd3cb75e6/
HTML
<a href="http://www.codesend.com/view/5f9903cf5257627ee1801b4fd3cb75e6/">Mouse.java</a>
BBCode
[url=http://www.codesend.com/view/5f9903cf5257627ee1801b4fd3cb75e6/]Mouse.java[/url]
© 2010 CodeSend.com - send code quick and easy
Syntax highlighting by Alex Gorbatchev
Syntax highlighting by Alex Gorbatchev
