颜色吸管的程序怎么写呀

04-11-18 天外星
就像PS中的颜色吸管一样,用这个工具在屏幕或窗口上任何一个地方单击,就可以取得单击处的颜色。各位大侠能否给个思路,在JAVA中该如何实现这个功能,如果有源码以供交流的那更好了。

天外星
2004-11-19 21:55
我找到一个取色的源码,可惜在编译的时候出错
请问MouseInfo是一个什么类?
请大家指点迷津

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;
}

}

天外星
2004-11-19 22:04
下面是我自己参考写的,可以达到取色的目的,不过有一个bug,运行后不能移动程序窗口,一旦移动,用鼠标取的颜色就不是当前窗口的,而是当前屏幕的.最小化窗口和最大化窗口倒是没这问题.
请问如何解决这个问题?

import java.awt.*;
import java.awt.event.*;
import java.awt.AWTException;

public class PickColor
extends Frame {

int xx, yy;
Robot robot;
Color pixel = new Color(0, 0, 0);
int R, G, B;
Image im;

public PickColor() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

MediaTracker tracker = new MediaTracker(this);
im = Toolkit.getDefaultToolkit().getImage("consult.jpg");
tracker.addImage(im, 0);
try {
tracker.waitForAll();
}
catch (InterruptedException e) {
e.printStackTrace();
}


addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
xx = e.getX();
yy = e.getY();
press_mouse();
//Graphics g = getGraphics();
//g.drawString(String.valueOf(e.getX()) + "/" + String.valueOf(e.getY()),
// e.getX(), e.getY());
//g.drawString(String.valueOf(pixel),300, 300);
repaint();
}
});

}

public Color press_mouse() {
try {
robot = new Robot();
}
catch (AWTException e) {
e.printStackTrace();
System.exit(1);
}
pixel = robot.getPixelColor(xx, yy);
R = pixel.getRed();
G = pixel.getGreen();
B = pixel.getBlue();
return (pixel);
}

public void paint(Graphics g) {
g.drawImage(im, 20, 50, this);
g.drawString(String.valueOf(R)+"+"+String.valueOf(G)+"+"+String.valueOf(B),300, 300);
}


public static void main(String[] args) {
PickColor f = new PickColor();
f.setSize(500, 400);
f.show();
}
}