1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class TestColorGrab {
private static final String NOM_FICHIER_IMAGE = "suricate.png";
public static void main(String[] args) {
try {
new TestColorGrab();
} catch (AWTException e) {
e.printStackTrace();
}
}
public TestColorGrab() throws AWTException {
JFrame frame = new JFrame("Grab color");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// composant dont on veut récupérer la couleur
Component component = createComponent();
// composant pour afficher la couleur
JPanel colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(24,24));
colorPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// layout principal
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(component, BorderLayout.CENTER);
mainPanel.add(colorPanel, BorderLayout.SOUTH);
frame.getContentPane().add(mainPanel);
Robot robot = new Robot();
component.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
Point point = e.getComponent().getLocationOnScreen();
point.x += e.getX();
point.y += e.getY();
Color color = robot.getPixelColor(point.x, point.y);
colorPanel.setBackground(color);
}
});
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Component createComponent() {
// un arrière-plant avec dégradé
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
Paint paint = new GradientPaint(new Point(0,0), Color.RED, new Point(0, getHeight()), Color.YELLOW);
((Graphics2D)g).setPaint(paint);
g.fillRect(0, 0, getWidth(), getHeight());
}
};
panel.setLayout(new BorderLayout());
// un avant-plan avec image
JLabel label = new JLabel(new ImageIcon(NOM_FICHIER_IMAGE));
panel.add(label, BorderLayout.CENTER);
return panel;
}
} |
Partager