GridFiller Applet Write an applet that displays a 4X4 grid. …

GridFiller Applet Write an applet that displays a 4X4 grid. When the user clicks on a square in the grid, the applet should draw a filled circle in it. If the square already has a circle, clicking on it should cause the circle to disappear.

Answer

Solution Approach: The problem requires implementing an applet that displays a 4X4 grid. The applet should allow the user to click on a square in the grid to draw a filled circle in it. If the square already has a circle, clicking on it should remove the circle.

To achieve this, we will use the Java Applet class provided by Java.awt package. The Applet class provides methods and components for creating graphical user interfaces. We will use the MouseListener interface to detect mouse clicks on the grid squares and the Graphics class to draw and remove circles.

Implementation Steps:
1. Create a new Java class and extend it from the Applet class.
2. Implement the MouseListener interface by importing the java.awt.event package.
3. Override the init() method of the Applet class to initialize the applet and set up the grid.
4. Override the paint() method to handle drawing and removing circles.
5. Implement the mouseClicked() method from the MouseListener interface to handle square clicks and draw or remove circles.
6. Use the fillOval() method from the Graphics class to draw circles in the clicked squares.
7. Use the clearRect() method from the Graphics class to remove circles from the clicked squares.

Here is the sample code for the implementation:

“`java
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class GridFillerApplet extends Applet implements MouseListener {

int[][] grid;
int squareSize;

public void init() {
setSize(400, 400);
grid = new int[4][4];
squareSize = getWidth() / 4;
addMouseListener(this);
}

public void paint(Graphics g) {
for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (grid[i][j] == 1) { g.setColor(Color.RED); g.fillOval(j * squareSize, i * squareSize, squareSize, squareSize); } } } } public void mouseClicked(MouseEvent e) { int row = e.getY() / squareSize; int col = e.getX() / squareSize; if (grid[row][col] == 1) { grid[row][col] = 0; // Remove the circle if already present } else { grid[row][col] = 1; // Draw a circle if not present } repaint(); // Redraw the grid } // Other methods of MouseListener interface (mousePressed, mouseReleased, mouseEntered, mouseExited) can be left empty } ``` This is a basic implementation of the GridFiller Applet. You can compile and run this code to see the applet in action.

Do you need us to help you on this or any other assignment?


Make an Order Now