import java.awt.Graphics; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseMotionListener; import java.util.Scanner; public class FloodFill { public static final int HEIGHT = 40; public static final int WIDTH = 40; public static DrawingPanel panel; // panel.getColor(x, y) -> the color at pixel x, y */ // panel.sleep(120) -> tells the DrawingPanel to update itself // and slow down; so, we can watch! public static void paintbucket(int x, int y, Color toFill) { if (x >= 0 && y >= 0 && x < HEIGHT && y < WIDTH && panel.getColor(x, y).equals(toFill)) { pencil(x, y); panel.sleep(120); paintbucket(x - 1, y, toFill); paintbucket(x, y - 1, toFill); paintbucket(x + 1, y, toFill); paintbucket(x, y + 1, toFill); paintbucket(x - 1, y - 1, toFill); paintbucket(x + 1, y + 1, toFill); paintbucket(x + 1, y - 1, toFill); paintbucket(x - 1, y + 1, toFill); } } public static void pencil(int x, int y) { Graphics g = panel.getGraphics(); g.setColor(Color.GREEN); g.fillRect(x, y, 1, 1); } public static void main(String[] args) { panel = new DrawingPanel(WIDTH, HEIGHT); panel.zoom(10); /* Draw a figure so we have something to paint. */ drawFigure(HEIGHT / 2); /* * Make the DrawingPanel use the "paintbucket tool" when the user clicks * on a pixel. */ panel.addMouseListener((MouseListener) new MouseAdapter() { public void mouseClicked(MouseEvent e) { int x = e.getX() / panel.getZoom(); int y = e.getY() / panel.getZoom(); paintbucket(x, y, panel.getColor(x, y)); } }); /* * Make the DrawingPanel use the "pencil tool" when the user drags * across pixels. */ panel.addMouseMotionListener((MouseMotionListener) new MouseAdapter() { public void mouseDragged(MouseEvent e) { pencil(e.getX() / panel.getZoom(), e.getY() / panel.getZoom()); } }); } public static void drawFigure(int multiplier) { Graphics g = panel.getGraphics(); g.setColor(Color.RED); g.fillRect(0, 0, 2 * multiplier, 2 * multiplier); g.setColor(Color.WHITE); g.fillOval(0, 0, 2 * multiplier, 2 * multiplier); g.setColor(Color.BLACK); g.drawRect(0, 0, 2 * multiplier, 2 * multiplier); g.drawOval(0, 0, 2 * multiplier, 2 * multiplier); g.drawLine(0, 0, 2 * multiplier, 2 * multiplier); g.drawLine(0, 2 * multiplier, 2 * multiplier, 0); g.drawLine(0, 1 * multiplier, 2 * multiplier, 1 * multiplier); g.drawLine(1 * multiplier, 0, 1 * multiplier, 2 * multiplier); } }