/* GraphicsCanvasのRobot利用の修正。 1.フィールド宣言を以下のように修正。 public class GraphicCanvas extends Canvas { Image offScreen; Robot r2d2; Rectangle rect1,rect2; 2.fillPaintとgetPixelを新しいものに書き換える。 ※以下は、新しくしたクラスのソースコード。 */ import java.awt.*; import java.awt.event.*; import java.util.*; import java.awt.image.*; public class GraphicCanvas extends Canvas { Image offScreen; Robot r2d2; Rectangle rect1,rect2; public GraphicCanvas() { super(); try{ r2d2 = new Robot(); } catch(Exception ex){} addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { fillPaint(e.getX(),e.getY(),Color.red); //printClickLoc(e.getX(),e.getY()); } }); } // 推奨サイズの設定 public Dimension getPreferredSize() { return new Dimension(200,200); } // ペイント処理 public void fillPaint(int w, int h,Color c) { if (r2d2 == null) { System.out.println("Robot is not here."); return; } if (offScreen == null) { offScreen = createImage(getSize().width,getSize().height); } int x1,x2,y; int thisW = getSize().width; int thisH = getSize().height; boolean flg = false; rect1 = getParent().getBounds(); rect2 = getBounds(); Point p; Color c1,c2; c1 = getPixel(w,h); Graphics g = offScreen.getGraphics(); Graphics g2 = getGraphics(); g2.setColor(Color.red); Stack st = new Stack(); st.push(new Point(w,h)); g.setColor(c); do { p = (Point)st.pop(); x1 = p.x; x2 = p.x; y = p.y; if (c.equals(getPixel(x1,y))) continue; while(true) { x1--; if (x1 < 0) break; c2 = getPixel(x1,y); if (!c1.equals(c2)) break; } x1++; while(true){ x2++; if (x2 >= thisW) break; c2 = getPixel(x2,y); if (!c1.equals(c2)) break; } x2--; g.drawLine(x1,y,x2,y); g2.drawLine(x1,y,x2,y); flg = false; if (y >= 0) { for(int i = x1; i <= x2; i++) { if (i >= thisW) break; c2 = getPixel(i,y - 1); if (c1.equals(c2)) { if (!flg) st.push(new Point(i,y - 1)); flg = true; } else flg = false; } } flg = false; if (y < thisH - 1) { for(int i = x1; i <= x2; i++) { if (i >= thisW) break; c2 = getPixel(i,y + 1); if (c1.equals(c2)) { if (!flg) st.push(new Point(i,y + 1)); flg = true; } else flg = false; } } } while(!st.empty()); g.dispose(); g2.dispose(); repaint(); } // クリック地点のColorを得る public Color getPixel(int x,int y) { Color c1 = r2d2.getPixelColor(x + rect1.x + rect2.x,y + rect1.y + rect2.y); return c1; } public void paint(Graphics g) { if (offScreen == null) offScreen = createImage(getSize().width,getSize().height); g.drawImage(offScreen,0,0,this); } }