'Changing the background color on mouse event

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


Solution 1:[1]

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

Now you need to count if the click was outside the bounds of rectangle.

Solution 2:[2]

In the mouseClicked method, you should test that e.getX() and e.getY() are outside the rectangle, and then invoke setBackground() :

this.setBackground(Color.red);

The rectangle border will stay green (is that what you want?)

HTH

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dalius Å idlauskas
Solution 2 laher