i am working on a cod of (attaxx game),and i have a problem with the buttons
i can determine the co-ordinates (x,y) of the button and i want to change its background color but i do not have a reference of the jbutton object it self.is there is any way to get a reference of the button using its coordinates.and this is a part of the code but it give a null pointer exception.

public void CompTurn()
    System.out.println(">>>>>>>>>>>>>>in comp turn");    
      int xg=getx1();
      int yg=gety1();
      int xb=0;
      int yb=0;
      int xx1=0;int xx2=0; int xx3=0;int xx4=0;int xx5=0;int xx6=0;int xx7=0;int xx8 =0;//for green
      int yy1=0;int yy2=0;int yy3=0;int yy4=0;int yy5=0;int yy6=0;int yy7=0;int yy8=0;
      xx1=xg-width; //1 
      xx3=xg+width; //3 
      yy5=yg;  //5                
      yy4=yg;  //4 
      xg=xx7; //7 
      xg=xx2; //2 
      for(int i=0 ;i<49; i++)  // a loop to searsh about a blue squre to move it
          if((button[i].getBackground()).equals(new Color(0,0,204)))
              xb=button[i].getX();//getting the coordinates of this square
              System.out.println(" the value of xb= "+xb+" yb= "+yb);    
              //*************************************move aroud the last position   of green ball step by one square
             //if the coordinate of this button is match with the coordinates of the last play of the human player (with green square)
               if( ((xb==xx7)&&(yy7==yb+height))){
                System.out.println("move aroud the last position of green ball step by one square");
                button[i].getComponentAt(xx7,yy7).setBackground(new Color(0,0,204)); 
// get the refrence of the button whic have this coordinates    
                turn=true;          // putting the flage=true to allow the human o play
                FinalResult();      //calling for finalresalt
                break;              //to stop the loop when the play is happened

What components are in your button[] array? Are they not the JButtons? If they are, you aleady have the button reference - it's button.

If that's not what you have in button[], then you can call getComponentAt() on the frame or panel that contains the buttons to get the component at those coordinates. SwingUtilities has several additional methods for working with component coordinate spaces as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.