// Project FloodFill import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyPanel extends JPanel { private boolean[][] array; private boolean curveCompleted; private int xStart, yStart; public MyPanel() { addMouseMotionListener(new MML()); addMouseListener(new ML()); reset(); } public void reset() { int x, y; array = new boolean[80][80]; for(x = 0; x <= 79; x++) for(y = 0; y <= 79; y++) array[x][y] = false; for(x = 0; x <= 79; x++) { array[x][0] = true; array[x][79] = true; } for(y = 0; y <= 79; y++) { array[0][y] = true; array[79][y] = true; } curveCompleted = false; repaint(); } public void startFill() { fill(xStart, yStart); repaint(); } public void fill(int x, int y) { if (!array[x][y]) { array[x][y] = true; fill(x + 1, y); // E fill(x, y - 1); // N fill(x - 1, y); // W fill(x, y + 1); // S } } public void paintComponent(Graphics g) { super.paintComponent(g); int x, y; g.setColor(Color.white); g.fillRect(0, 0, 400, 450); g.setColor(Color.blue); for(x = 0; x <= 79; x++) for(y = 0; y <= 79; y++) if (array[x][y]) g.fillRect(5*x, 5*y, 5, 5); if (curveCompleted) { g.setColor(Color.red); g.fillRect(5*xStart, 5*yStart, 5, 5); } } private class MML implements MouseMotionListener { public void mouseDragged(MouseEvent e) { int x, y; x = e.getX() / 5; y = e.getY() / 5; if (!array[x][y]) { array[x][y] = true; repaint(); } } public void mouseMoved(MouseEvent e) {} } private class ML implements MouseListener { public void mouseReleased(MouseEvent e) { if (curveCompleted) { xStart = e.getX() / 5; yStart = e.getY() / 5; repaint(); } else curveCompleted = true; } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} } }