更改鼠标事件的背景颜色

时间:2011-10-30 22:08:00

标签: java applet mouseevent awt

我希望在矩形外部单击鼠标时更改背景颜色。我只是不知道如何使用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) {}
}

2 个答案:

答案 0 :(得分:0)

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class AnAppletWithMouseEvents extends Applet implements MouseListener {
Color color = Color.green;
public void init()
{
    addMouseListener(this);
}
public void paint(Graphics g)
{

    g.setColor(this.color);
    g.drawRect(10, 30, 150, 150);
}
public void mouseClicked(MouseEvent e)
{
    this.color = color.red;
    this.repaint();

}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}

现在你需要计算点击是否在矩形范围之外。

答案 1 :(得分:0)

mouseClicked方法中,您应该测试e.getX()e.getY()是否在矩形之外,然后调用setBackground()

this.setBackground(Color.red);

矩形边框会保持绿色(这就是你想要的吗?)

HTH