Reputation: 3341
My homework is
Write an applet that draw the house shown on the left in Figure 14-32. When the user clicks on the door or windows, they should close. The figure on the right shows the house with its door and windows closed.
I basically want a Java Applet where, if a user clicks on a rectangle, another one is sudden created and drawn.
Here is my code so far.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test2 extends JApplet
{
private final int currentX = 0;
public void init()
{
addMouseListener(new MyMouseListener());
}
public void paint (final Graphics g)
{
super.paint (g);
g.drawRect(100, 100, 200, 200);
}
private class MyMouseListener extends MouseAdapter
{
currentX = e.getX();
}
}
Upvotes: 0
Views: 1949
Reputation: 274612
Take a look at the Java Tutorial | How to Write a Mouse Listener. It will help you determine when and where a user clicks. Once you have these (x,y) coordinates you can check if they lie within the window or the door and if so, draw something else.
Sample code:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
//check if (x,y) lie in a certain rectangle
if(x>100 && x<300 && y>100 && y<300){
//set a variable and repaint
closeDoors = true;
repaint();
}
}
In your paint method, you need to check if the closeDoors
variable is set and if so, draw something else.
public void paint (final Graphics g){
super.paint (g);
g.drawRect(100, 100, 200, 200);
if(closeDoors){
g.fillRect(100, 100, 200, 200);
}
}
Upvotes: 1
Reputation: 114777
When the user clicks on the door or windows, then you check if the mouse coordinates are inside the window or door area and, if yes, you replace the drawing of an open door or open window by a drawing of a closed one, which then will look like: they should close.
So, that's what you have to do:
Tip: your current implementation of MouseListener doesn't work at all. You have to override methods from MouseAdapter
and put your test in the appropriate method.
Upvotes: 0