Code 1. Prints the screen color of the current mouse on the screen.
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;
}
}
Code 2. Using a GUI, output the screen color of the current mouse, and change the background colors of the 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 it 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 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 <= or G <= or B <= 50
Graphics g = p.getgraphics ();
if (c.getred () <=50 | | c.getgreen () <= | | 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;
}
}