当在一个组件上按下,释放,点击,移动或拖动鼠标时就会产生鼠标事件。MouseEvent对象捕获这个事件.
MouseEvent类继承InputEvent类,所以MouseEvent对象可以使用InputEvent类中定义的方法。
java.awt.point类表示一个点,该类包含两个用来表示坐标的公共变量x和y。
为了创建一个point,可以使用Point(int x,int y)
InputEvent类中的方法:
getWhen(): long 返回事件发生的时间
isAltDown(): boolean 如果按下alt返回true
isControlDown(): boolean 如果按下ctrl返回true
isShiftDown(): boolean 如果按下shift返回true
MouseEvent类中的方法:
getButton(): int 表明是否点击鼠标按钮
getClickCount(): int 返回相关事件的鼠标点击数
getPoint(): java.awt.point 返回包含X坐标和Y坐标的point对象
getX():int 返回鼠标点的X
getY(): int 返回鼠标点的Y
java提供了两个处理鼠标事件的监听器接口MouseListener和MouseMotionListener。
实现MouseListener接口可以监听鼠标的按下,释放,输入,退出和点击动作。
实现MouseMotionListener接口可以监听拖动鼠标和鼠标的移动动作。
mousePressed(e: MouseEvent): void 在源组件上按下鼠标按钮
mouseReleased(e: MouseEvent): void 释放源组件上的鼠标按钮
mouseClicked(e: MouseEvent): void 在源组件上点击鼠标按钮
mouseEntered(e: MouseEvent): void 在鼠标进入源组件之后被调用
mouseExited(e: MouseEvent): void 在鼠标退出源组件之后被调用
mouseDragged(e: MouseEvent): void 按下按钮移动鼠标按钮之后被调用
mouseMoved(e: MouseEvent): void 不按住按钮移动鼠标之后被调用
实现一个程序,在面板中显示一条信息,可以用鼠标移动这条信息,信息会随着鼠标的移动而移动,信息总是显示在指针处。
example
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Swing {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame win=new JFrame("我的第一个窗口");
win.setSize(250, 200);
JButton button=new JButton("我是一个按钮");
ButtonMonitor montor =new ButtonMonitor();
button.addActionListener(montor);
Mouse mouse=new Mouse();
win.addMouseListener(mouse);
JPanel panel=new JPanel();
panel.add(button);
win.setContentPane(panel);
win.setVisible(true);
WinFrame window=new WinFrame();
window.setVisible(true);
window.setLocation(300, 300);
String[] font=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
System.out.println("Length="+font.length);
}
}
class WinFrame extends JFrame
{
public WinFrame()
{
super();
this.setTitle("我是一个窗口");
this.setSize(250, 400);
this.setBackground(getBackground());
}
}
class ButtonMonitor implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Button Click!");
}
}
class Mouse implements MouseListener
{
public int x,y;
public void mouseEntered(MouseEvent e)
{
System.out.println("mouse entered!");
}
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
System.out.println("point.x="+x+" "+"point.y="+y+";");
}
public void mouseClicked(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
}
// note 这里的几个mouse的函数都需要重新定义.
转载于:https://blog.51cto.com/shuoailin/1435005