[英]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.
编写一个绘制图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. 我基本上想要一个Java Applet,如果用户单击一个矩形,则会突然创建并绘制另一个。
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 | 看看Java教程| 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.
获得这些(x,y)坐标后,您可以检查它们是否位于窗户或门内,如果有,请绘制其他东西。
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. 在绘画方法中,您需要检查
closeDoors
变量是否已设置,如果已设置,请绘制其他内容。
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: 因此,这就是您要做的:
Tip : your current implementation of MouseListener doesn't work at all. 提示 :您当前的MouseListener实现根本不起作用。 You have to override methods from
MouseAdapter
and put your test in the appropriate method. 您必须从
MouseAdapter
重写方法,然后将测试放入适当的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.