文本关键字:程序设计/java/入门
声明:
本文核心代码选择自langzi84的blog请看以下链接
http://dev.csdn.net/article/44/article/44/44529.shtm
http://blog.csdn.net/langzi84/archive/2004/10/21/146331.aspx
代码1。在屏幕上输出当前鼠标所在的屏幕颜色。
import java.awt.*;
public class pickcolor {
public static void main(string[] args) {
pickcolor pc = new pickcolor();
color color = pc.pickcolor();
system.out.println("color = "+color);
}
public color pickcolor() {
color pixel = new color(0,0,0);
robot robot = null;
point mousepoint;
int r,g,b;
// mouseinfo mouseinfo = new mouseinfo();
try {
robot = new robot();
} catch (awtexception e) {
e.printstacktrace();
system.exit(1);
}
mousepoint = mouseinfo.getpointerinfo().getlocation();
pixel = robot.getpixelcolor(mousepoint.x,mousepoint.y);
r = pixel.getred();
g = pixel.getgreen();
return pixel;
}
}
代码2。使用一个gui,输出当前鼠标所在的屏幕颜色,并改变gui的背景色。
// create by kin 2004/10/24 refer to http://dev.csdn.net/article/44/44529.shtm
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class pickcolor2 extends jframe {
public static void main(string[] args) {
pickcolor2 pc = new pickcolor2();
//color color = pc.pickcolor();
//system.out.println("color = "+color);
}
public pickcolor2 () {
super("pick color");
setsize(200,200);
jpanel p =new jpanel();
getcontentpane().add(p);
// this mouse listener only is limited in the java desktop region
p.addmousemotionlistener(new pickcolormouesmotionlistener(p));
// this thread is really effected!
new pickcolorthread(p).start();
setvisible(true);
}
/**mouse motion listener,when mouse are moving, then set corresping screens color to the jpanels background color. */
class pickcolormouesmotionlistener extends mousemotionadapter {
private jpanel p = null;
pickcolormouesmotionlistener(jpanel p) {
this.p = p;
}
public void mousemoved(mouseevent e) {
color c = pickcolor();
this.p.setbackground(c);
//system.out.println (c);
}
}
class pickcolorthread extends thread {
private jpanel p = null;
pickcolorthread(jpanel p){
this.p=p;
}
public void run () {
while (true) {
try {
thread.currentthread().sleep(10);
color c = pickcolor();
this.p.setbackground(c);
// try change the foreground when background s r <= 50 or g <= 50 or b <= 50
graphics g = p.getgraphics ();
if (c.getred() <=50 || c.getgreen() <= 50 || c.getblue() <= 50) {
g.setcolor(color.white);
} else {
g.setcolor(color.black);
}
g.drawstring(c.tostring(),0,100);
g = null;
//system.out.println (c);
} catch (interruptedexception e) {
e.printstacktrace();
system.exit(1);
}
}
}
}
/**get screen color*/
public color pickcolor() {
color pixel = new color(0,0,0);
robot robot = null;
point mousepoint;
int r,g,b;
// mouseinfo mouseinfo = new mouseinfo();
try {
robot = new robot();
} catch (awtexception e) {
e.printstacktrace();
system.exit(1);
}
mousepoint = mouseinfo.getpointerinfo().getlocation();
pixel = robot.getpixelcolor(mousepoint.x,mousepoint.y);
r = pixel.getred();
g = pixel.getgreen();
return pixel;
}
}
闽公网安备 35060202000074号