Java Robot Class | Get the pixel Color of a given point
Last Updated :
14 Apr, 2021
Robot is part of java.awt package . Robot class is basically used to generate native system input events for the purposes of self- running demos, test automation, and other application where control over mouse and keyboard is used.
Robot class generates events that can be used to control mouse, keyboard and can be used to take screenshot of the screen.
In this article we will discuss how to get the pixel color of the point on the screen mentioned by the user.
Method used :
getPixelColor(int x, int y)
This function returns an object of the color class
of the given screen coordinates.
In the following program we will print a label that will contain the RGB values of the pixel entered and the text of the label will be of the pixel Color
Java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class color extends JFrame
implements ActionListener {
static JTextField x, y;
static JButton b;
static JFrame f;
static JLabel l;
public static void main()
{
f = new JFrame( "pixel Color" );
l = new JLabel( "no value" );
x = new JTextField( 16 );
y = new JTextField( 16 );
b = new JButton( "find" );
color co = new color();
b.addActionListener(co);
JPanel p = new JPanel();
p.add(x);
p.add(y);
p.add(b);
p.add(l);
f.add(p);
f.setSize( 500 , 500 );
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals( "find" )) {
int xp, yp;
xp = Integer.parseInt(x.getText());
yp = Integer.parseInt(y.getText());
try {
Robot r = new Robot();
c = r.getPixelColor(xp, yp);
}
catch (Exception evt) {
System.err.println(evt.getMessage());
}
Color c;
l.setForeground(c);
l.setText( "Red = " + c.getRed() + ",
Green = " + c.getGreen() + " , Blue = " + c.getBlue());
}
}
}
|
Output :
Note : the following program might not run in an online compiler please use an offline IDE.
Share your thoughts in the comments
Please Login to comment...