/** Robotによる自動操縦とスクリーンキャプチャ取得 2007/12/31 宍戸 輝光 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.image.*; public class JRobot extends JFrame implements ActionListener { private ImageIcon _img; private JLabel _view; private JButton _btnGo; public JRobot() { // 表示用イメージアイコン作成 Image img = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); _img = new ImageIcon(img); // イメージアイコンを保持するラベル作成 _view = new JLabel(_img); // testボタン作成 _btnGo = new JButton("test"); _btnGo.addActionListener(this); Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS)); c.add(_view); c.add(_btnGo); setSize(240, 240); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } // ボタンが押されたら、test()を呼び出す public void actionPerformed(ActionEvent e) { test(100, 100); } // (x, y)にマウスカーソルを移動し周辺のスクリーンキャプチャを保存 private void test(int x, int y) { Robot r = null; // Robotオブジェクト作成 try { r = new Robot(); } catch (Exception e) { } if (r == null) { return; } // マウスカーソル移動 r.mouseMove(x, y); int width = _img.getIconWidth(); int height = _img.getIconHeight(); int px = x - width / 2; int py = y - height / 2; if (px < 0) { px = 0; } if (py < 0) { py = 0; } // (px, py)からwidth*heightピクセルのスクリーンキャプチャ画像を取得 BufferedImage img = r.createScreenCapture(new Rectangle(px, py, width, height)); // 取得した画像をイメージアイコンに設定 _img.setImage(img); // ラベルにアイコンを設定し再描画 _view.setIcon(_img); _view.repaint(); } public static void main(String stArgs[]) { new JRobot(); } }