tags:

views:

68

answers:

3

Hi everyone,

I am currently in the process of making a java minesweeper game for school and have run into a problem. I have created an array of 64 buttons arranged in a grid layout. The problem i am having is getting the x and y co-ordinates of a particular button pressed and sending these co-ordinates to another class which contains a 2d array. any suggestions on how i can obtain the x and y position of the button pressed??? any help on this matter would be greatly appreciated

thanks

A: 

I would suggest you not to use buttons instead you can use a frame and as background you can put an image showing button view

and then you can retrieve location using

          private void showMousePos(MouseEvent e) {
            JLabel src = (JLabel)e.getComponent();
            PointerInfo pointerInfo = MouseInfo.getPointerInfo();
            Point point = pointerInfo.getLocation();
            src.setText(point.toString());
          }
org.life.java
A: 

Once you know the click position you can use basic math to get the square hit. Then it's object-oriented programming to give that info to other parts of the game. You could follow a MVC (Model View Controller) pattern.

Basically your controller (main part) will register as listening to your view (your button(s)).

Here is a similar game with source code included if it helps.

Wernight
that helps me a lot, thanks
mrblippy
A: 

Do you need the x-y coordinates on the canvas or just the x and y as in which column/row the button is?

If it's the latter just ensure that the other class can listen to events, and fire an event with the coordinates.

class OtherClass {
     public void fireEvent(MineSweepButton button);
}

and for your button:

class MineSweepButton extends JButton {
     private int x;
     private int y;

     public MineSweepButton(String text, int x, int y) {
           super(text);
           this.x = x;
           this.y = y;               
     }
}

Now add an action listener that fires an event on the OtherClass.

Jes