I have been given an assignment where I need to make an Applet that draws a house and if you click on either the door, right window, or left window, that object becomes black. I've got the house to be drawn fine by trial and error and I got the mouse events to work, but it is not working correctly. When I run a test, it fills the whole applet instead of that shape with all black. How do I get this to work properly?
This is the code I typed up:
When I asked on another forum, somebody suggested using the paintComponent() method, but I could not compile it and did not know how to use that method. The code used to extend the JApplet class, but it was changed to the Applet class. Also, when I type
The compiler does not know that it has been used already, because it says variable "g" cannot be found. I also tried
This at least recognized the "g" variable, but it wanted a semi-colon to be entered.
This is the code I typed up:
Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class House extends Applet
{
public void init()
{
setBackground(Color.WHITE);
addMouseListener(new MyMouseListener());
}
public void paint(Graphics g)
{
super.paint(g);
// roof
g.drawLine(156, 99, 0, 150);
g.drawLine(156, 99, 299, 150);
g.drawLine(0, 150, 299, 150);
// base
g.drawRect(3, 150, 296, 110);
// window left
g.drawRect(50, 155, 50, 70);
g.drawLine(50, 185, 100, 185);
g.drawLine(75, 155, 75, 225);
// door
g.drawRect(120, 155, 50, 100);
g.fillOval(158, 200, 5, 10);
// window right
g.drawRect(200, 155, 50, 70);
g.drawLine(200, 185, 250, 185);
g.drawLine(225, 155, 225, 225);
}
private class MyMouseListener implements MouseListener
{
public void mousePressed(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
int currentx = e.getX();
int currenty = e.getY();
boolean WindowLeft = (currentx >= 50 && currentx < 77 && currenty >= 155 && currenty <= 225);
if (WindowLeft)
{
setBackground(Color.BLACK);
repaint();
}
else;
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}
}
When I asked on another forum, somebody suggested using the paintComponent() method, but I could not compile it and did not know how to use that method. The code used to extend the JApplet class, but it was changed to the Applet class. Also, when I type
Code:
g.setBackground(Color.BLACK);
The compiler does not know that it has been used already, because it says variable "g" cannot be found. I also tried
Code:
House g.setBackground(Color.BLACk);
This at least recognized the "g" variable, but it wanted a semi-colon to be entered.