更改鼠标事件的背景颜色
我想在鼠标单击矩形外部时更改背景颜色。我只是不知道如何使用 MouseEvent。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithMouseEvents extends Applet implements MouseListener {
public void init()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.drawRect(10, 30, 150, 150);
}
public void mouseClicked(MouseEvent e)
{
String clickDesc;
if (e.getClickCount() == 2)
clickDesc = "double";
else
clickDesc = "single";
System.out.println("Mouse was " + clickDesc + "-clicked at location (" +
e.getX() + ", " + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
I want to change the background color when the mouse is clicked on the outside of the rectangle. I just dont know how to use the MouseEvent.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithMouseEvents extends Applet implements MouseListener {
public void init()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.drawRect(10, 30, 150, 150);
}
public void mouseClicked(MouseEvent e)
{
String clickDesc;
if (e.getClickCount() == 2)
clickDesc = "double";
else
clickDesc = "single";
System.out.println("Mouse was " + clickDesc + "-clicked at location (" +
e.getX() + ", " + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
mouseClicked
方法中,您应该测试e.getX()
和e.getY()
是否位于矩形之外,然后调用 < code>setBackground() :this.setBackground(Color.red);
矩形边框将保持绿色(这是你想要的吗?)
HTH
In the
mouseClicked
method, you should test thate.getX()
ande.getY()
are outside the rectangle, and then invokesetBackground()
:this.setBackground(Color.red);
The rectangle border will stay green (is that what you want?)
HTH
现在您需要计算点击是否在矩形边界之外。
Now you need to count if the click was outside the bounds of rectangle.