-1

I'm trying to draw a game map using many rectangular shapes(just like a screen contains many pixels). I'm using graphics 2D and fillRect(int x, int y, width, height) method. I make the rectangular so small with 10 widths and 10 height.

How can I detect if someone clicks a rectangle? I have read other questions but I am still confused by how the mouse listener detects my small rectangle?

Can someone give me any other solution instead of making pixels with a rectangular shape? maybe like buttons or something?

Here is my example code of making multiple rectangle :

public void paint (Graphics g){

Graphics2D g2D = (Graphics2D) g;
for (int j = 0; j<Map.WIDTH; j++){
    if(j==100){
            if(map[i][j]=='#'){
                x=50;
                y+=10;
                g2D.setColor(Color.BLACK);
                g2D.fillRect(x, y, 10, 10);
                x+=10;
                y+=0;   

                    }

note: just ignore the iteration because i'm iterate from some input file(a template)

arvinrdty
  • 7
  • 2
  • 2
    Welcome to Stack Overflow, please take the [tour] and go through the [help], learn [ask] and post a valid [mcve] that demonstrates your attempt to do this – Frakcool May 16 '17 at 15:45
  • 1
    1) That's not a [mcve], (re)read the link please. 2) I guess you're extending JFrame and that's why you're overriding `paint(...)` and not `paintComponent(...)`. 3) Read the [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/painting/) on custom painting carefully. 4) Always call `super.paint()` (Or `super.paintComponent()` if following tip #2) as the first line in your method... – Frakcool May 16 '17 at 17:59

1 Answers1

0

Is it a class that extends JPanel ? Generally you have to set your listener on your JPanel or whatever:

 void setListener(MouseListener listener) {
    myPanel.addMouseListener(listener);
}

then in your listenerClass you do something like that :

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

class ControlButton extends MouseAdapter {

private MyViewClass view;

ControlButton(MyViewClass view) {
    this.view = view;
    view.setListener(this);
}

@Override
public void mouseClicked(MouseEvent e) {

    //if my x and y point represent the upper left corner
    int rectX = view.getMyRectX();
    int rectY = view.getMyRectY();
    int rectWidth = view.getRectWidth();
    int rectHeight = view.getRectHeight();
    if (e.getX() > rectX && e.getX() < rectX + rectWidth
            && e.getY() > rectY && e.getY() < rectY + rectHeight) {
        System.out.println("YES");
    }
}

}

Of course, I suppose you are working with Swing. If it is not what you want, please be more precise in your explanation ;)

cladlink
  • 31
  • 4