Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i'm trying to code a Minesweeping game and i need to detect if specific buton is pressed. Is there a way to do that?
Part of the code:

What I have tried:

Java
public int[] AddMines()
    {
        Random rnd=new Random();
        int mine_positions[]=new int[20]; 
        int i_counter []=new int[9];
        int j_counter[]=new int [9];
        int pos=0;
        for (int i=0; i<10; i++)
        {
            int rand_i = rnd.nextInt(9);
            i_counter[rand_i]++;
            int rand_j = rnd.nextInt(9);
            j_counter[rand_j]++;
            if(i_counter[rand_i]>1&&j_counter[rand_j]>1)
            {
                 rand_i = rnd.nextInt(9);
                 rand_j = rnd.nextInt(9);
            }
            if(pos<20)
            {
                mine_positions[pos]=rand_i;
                mine_positions[pos+1]=rand_j;
                pos+=2;
            }         
        }
        System.out.print(Arrays.toString(mine_positions));
        return mine_positions;
    }

    public boolean IsMine(int raw, int col)
    {
        int pos=0;
        for (int i=0; i<Raw; i++)
        {
            for (int j=0; j<Col; j++)
            {
                while(pos<20)
                {
                    if (mine_array[pos]==raw && mine_array[pos+1]==col)
                        return true;
                    pos+=2;
                    if(pos==19)
                        pos=0;
                }
            }
        }
        return false;
    }
    public void mouseClicked(MouseEvent e)
        {
            Button b = (Button) e.getSource();
            for (int i=0; i<Raw; i++)
            {
                for (int j=0; j<Col; j++)
                {
                    
                        if(e.getButton()==MouseEvent.BUTTON1) {
                            if (IsMine(i, j) == true) {
                                b.SetIm(mine.getImage());
                                b.repaint();
                            }

                        
                    }
                }
            }
Posted
Updated 22-Oct-22 0:41am
v2

1 solution

You should use MouseEvent.getPoint (Java Platform SE 7 )[^] to find out where the click occurred in your window.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900