Guillaume F. :
I'm trying to get the color of a Swing JFrame, for a chosen (x,y)
pixel of the component.
For example, I want to know the color of a given JFrame
at their (0,0)
point.
The reason is that my component is a partially transparent overlay, with a JPanel
underneath. For pixels that are opaque, the mouse events should be dealt by the overlay. For pixels that are transparent, the mouse events should instead be forwarded to the JPanel
underneath.
Is this a way to do this?
Sergiy Medvynskyy :
Yes it's possible. Use the function getColorAt
from the example below:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class GUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(GUI::startUp);
}
private static void startUp() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1020,760);
frame.setResizable(false);
frame.setLayout(new FlowLayout());
frame.getContentPane().setBackground(Color.BLUE);
JTextArea jta = new JTextArea(40,40);
jta.setEditable(false);
jta.setBackground(Color.WHITE);
frame.add(new JScrollPane(jta));
frame.setVisible(true);
SwingUtilities.invokeLater(() -> printColors(frame));
}
private static void printColors(JFrame frm) {
System.out.println("Color at (1, 1): " + getColorAt(frm, new Point(1, 1)));
System.out.println("Color at (300, 100): " + getColorAt(frm, new Point(300, 100)));
}
public static Color getColorAt(JFrame frm, Point p) {
Rectangle rect = frm.getContentPane().getBounds();
BufferedImage img = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_ARGB);
frm.getContentPane().paintAll(img.createGraphics());
return new Color(img.getRGB(p.x, p.y), true);
}
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=395031&siteId=1