kakadoodles
kakadoodles

Reputation: 19

How to detect a click event in an Image class in Java?

I'm practicing to learn Java by creating a simple game. In my simple game, I want to use the AWT image class, and I want to click the image class, and it will pop up a dialog box like alert,

public class Sample
{
    Image img = getImage(getClass().getResource("0.jpg"));

    void paint (Graphics g)
    {
        g.drawImage(img,30,30,this);
    }
}

I want that if I clicked that image the image will detect the click event and it will show an alert dialog box.

Upvotes: 2

Views: 10556

Answers (3)

npinti
npinti

Reputation: 52185

You could create a custom JPanel which has a background image (the image you want). You can then use the JPanel's functionality to listen for click events. A custom JPanel could be something like so (taken from here):

class ImagePanel extends JPanel {

    private Image img;

    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}

For more information on events, you can take a look at the Oracle tutorial How to Write a Component Listener.

Upvotes: 0

Nafiz Bayındır
Nafiz Bayındır

Reputation: 495

I wrote a function some days ago:

public boolean isBetween(float x1, float y1, float x2, float y2, float objeX, float objeY) {
    if ((x1 <= objeX && x2 >=objeX) || (x1 >=objeX && x2<=objeX )) {
        if ((y1 <= objeY && y2 >=objeY) || (y2 <= objeY && y1 >=objeY))
            return true;
    }
    else {
        return false;
    }
}

When you use it, give four points of the image. And the last two points are the clicked points. You must add a mouselistener. When event action, you check for the clicked point with isBetween function. If it returns true, you image was clicked.

Upvotes: 4

mKorbel
mKorbel

Reputation: 109813

It would be better to look for Icon/ImageIcon for displaying a picture in JLabel. Then you need only to add and override the proper method from MouseListener for listening to mouseclick for JLabel.

Upvotes: 8

Related Questions