Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.AWTException;
- import java.awt.Dimension;
- import java.awt.EventQueue;
- import java.awt.Graphics;
- import java.awt.MouseInfo;
- import java.awt.Point;
- import java.awt.Rectangle;
- import java.awt.Robot;
- import java.awt.event.MouseEvent;
- import java.awt.event.MouseMotionListener;
- import java.awt.image.BufferedImage;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- /** @see http://stackoverflow.com/questions/3742731 */
- public class Zoom extends JPanel implements MouseMotionListener {
- private static final int SIZE = 12;
- private static final int S2 = SIZE / 2;
- private static final int SCALE = 48;
- private BufferedImage img;
- private Robot robot;
- public Zoom() {
- super(true);
- this.setPreferredSize(new Dimension(SIZE * SCALE, SIZE * SCALE));
- img = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
- try {
- robot = new Robot();
- } catch (AWTException e) {
- e.printStackTrace(System.err);
- }
- }
- boolean ifdone = true;
- @Override
- protected void paintComponent(Graphics g) {
- if (ifdone) {
- ifdone = false;
- g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
- ifdone = true;
- }
- }
- @Override
- public void mouseMoved(MouseEvent e) {
- Point p = e.getPoint();
- int x = p.x * SIZE / getWidth();
- int y = p.y * SIZE / getHeight();
- int c = img.getRGB(x, y);
- this.setToolTipText(x + "," + y + ": " + String.format("%08X", c));
- }
- @Override
- public void mouseDragged(MouseEvent e) {
- final Point p = MouseInfo.getPointerInfo().getLocation();
- Rectangle rect = new Rectangle(p.x - S2, p.y - S2, SIZE, SIZE);
- img = robot.createScreenCapture(rect);
- repaint();
- }
- private static void create() {
- JFrame f = new JFrame("Click & drag to zoom.");
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- Zoom zoom = new Zoom();
- f.add(zoom);
- f.pack();
- f.setVisible(true);
- Ticker t = new Ticker(zoom);
- zoom.addMouseMotionListener(zoom);
- t.start();
- }
- private static class Ticker extends Thread {
- private final Robot robot;
- public boolean update = true;
- private final Zoom view;
- public Ticker(Zoom zoomPanel) {
- view = zoomPanel;
- try {
- robot = new Robot();
- } catch (AWTException e) {
- throw new RuntimeException(e);
- }
- }
- public void done() {
- update = false;
- }
- public void run() {
- while (update) {
- final Point p = MouseInfo.getPointerInfo().getLocation();
- Rectangle rect = new Rectangle(p.x - S2, p.y - S2, SIZE, SIZE);
- view.img = robot.createScreenCapture(rect);
- view.repaint();
- }
- }
- }
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- @Override
- public void run() {
- create();
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement