开发者

How can I react on Mouse events in a Java applet and then paint accordingly?

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();
    }
}


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);
    }
}


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:

  • the "house" model consists of a building, a door and a window, each represented by coordinates
  • "door" and "window" can be painted either in "open" or "close" mode
  • You need test method to check, if a mouse click occured "on" the windoww or "on" the door

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜