Question

Im trying to make it so when a button is clicked, I can change one of its properties.

class Tile extends Button{
  public int position[];
  public Tile(){
    super();
    position = 0;
  }

 }

Where initialized:

{
  Tile tiles [][] = new Tile[10][10];
  for(int i=0; i<10; i ++){
    for(int j =0; j<10; j++){
      tiles[i][j].position = i*10+j;
      tiles[i][j].addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent e) {
                    System.out.println(((Tile)(e.getSource())).position[1]); //this results in a null pointer
                }
            });
    }
  }
}

I'd like the program to print out the position value in the tile when it is clicked. Is there any way to access the object which the event is referring to? I really just need to know which tile in the array was clicked. edit: When I try to use e.getSource(), i get a NullPointerException

Was it helpful?

Solution

The position is declared an an Array, yet you use it an a Int.

Changing it to a simple int should fix your problem.

class Tile extends Button{
  public int position;
  public Tile(){
    super();
    position = 0;
  }

 }

The Initialization method:

{
  Tile tiles [][] = new Tile[10][10];
  for(int i=0; i<10; i ++){
    for(int j =0; j<10; j++){
      tiles[i][j].position = i*10+j;
      tiles[i][j].addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent e) {
                    System.out.println(((Tile)(e.getSource())).position);
                }
            });
    }
  }
}

OTHER TIPS

As stated by the user PeekaySwitch, you can get the source of the event triggered by the button, in which case it is the button. All you must do is apply a cast to get you the correct type of the desired object:

@Override public void handle(ActionEvent e) 
{
    Button button = (Button) e.getSource();
}

After doing this, you just need to get the object properties and handles them the way you want. Do not forget that the types of events in JavaFX are all part of the Java standard library.

With respect to its exception null value, you are making a basic mistake of language. The next code snippet you start the reference to the array of objects:

Tile tiles [][] = new Tile[10][10];

However, you are not starting the objects within the vector. Try to start each Tile object by doing the following:

tiles[i][j] = new Tile();

Place this code inside of nested loops, and before each Tile object being used.

Hope this helps you. Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top