Ⅰ 滑鼠如何進行編程
在java.awt.*包下面有一個Robot類,可以生成輸入事件,例如,Robot.mouseMove 將移動滑鼠游標
這個類除了模擬滑鼠鍵盤操作以外,還可以用來截取屏幕,只演示一下怎麼模擬滑鼠鍵盤操作,具體api參考javadoc。這個演示完成了彈出QQ和移動窗口的功能。代碼如下:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
/**
* @author bean
*
*/
public class RobotDemo {
private Robot robot = null;
public RobotDemo() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
/** 可以彈出QQ */
public void keyBoardDemo() {
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_Z);
robot.keyRelease(KeyEvent.VK_Z);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_ALT);
}
/** 前提是有個最大化的窗口,功能是移動到標題欄,然後拖拽到600,600的位置*/
public void mouseDemo(){
robot.mouseMove(80, 10);
robot.mousePress(KeyEvent.BUTTON1_MASK);
try {
Ⅱ Java程序運行後出現一張笑臉,滑鼠點擊一次則變成哭臉,再點擊一次又變成笑臉,依次輪換。
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class design extends Frame {
private String title = "笑臉";
design() {
this.setTitle("變臉小程序");
}
public void paint(Graphics g) {
g.drawArc(100, 200, 100, 60, 0, 180);
g.drawArc(260, 200, 100, 60, 0, 180);
if (!title.equals("笑臉")) {
g.drawArc(180, 260, 100, 60, 0, -180); // 畫弧---嘴巴
title = "笑臉";
} else {
g.drawArc(180, 260, 100, 60, 0, 180); // 畫弧---嘴巴
title = "哭臉";
}
g.drawString(title, 80, 100);
g.drawOval(80, 100, 300, 300);
}
public static void main(String args[]) {
design D = new design();
D.setSize(new Dimension(500, 500));
D.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
D.addMouseListener(new MouseClick(D));
D.setVisible(true);
}
}
class MouseClick implements MouseListener {// 實現滑鼠監聽事件
private design d;
public MouseClick() {
}
public MouseClick(design d) {
this.d = d;
}
public void mouseClicked(MouseEvent e) {// 這這里做滑鼠單機處理
// TODO Auto-generated method stub
if (d != null) {
d.repaint();
}
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
已經做好了,順便幫你調整一下格式