views:

133

answers:

2

Hi Gurus, We have a swing application which displays a lot of rectangles. We use Rectangle2D.double class to draw the rectangles on a JPanel. My requirement is this. Upon clicking the rectangle, I have to pick an image from the local filesystem and show it in a popup window or a frame. My question is how can I provide a hyperlink or button inside that Rectangle2D.double rectangle. Please let me know.

Thanks -Jad.

A: 

You want to put a MouseListener on the panel, that will catch all clicks anywhere on the panel. You can then get the location of the click from the event and determine which rectangle the click happened in, and then call up the code appropriate for that event and location.

Carl Smotricz
+1  A: 

I hope this is what you mean:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class RectButton extends JPanel {

    Rectangle2D.Double rect;

    public RectButton() {
        this.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                Point point = e.getPoint();
                System.out.println(checkRectArea(point));
                // Do whatever else you want here.
            }
        });
    }

    public boolean checkRectArea(Point point) {
        return rect.contains(point);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        rect = new Rectangle2D.Double(10, 10, 50, 50);
        g2.draw(rect);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        RectButton r = new RectButton();
        frame.add(r);
        frame.setSize(new Dimension(300, 300));
        frame.setVisible(true);
    }

}

This program draws a rectangle and print true if you clicked inside the rectangle, false otherwise.

Artur