setTO method is not working with error message NullpointerException import javaf
ID: 3720767 • Letter: S
Question
setTO method is not working with error message NullpointerException
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
public class TootAndOtto extends Application implements EventHandler<ActionEvent>{
private static TootAndOtto theObject;
private int row = 6;
private int col = 6;
private Button[][] button = new Button[col][row];
private boolean nextT = false;
private boolean clickMade = true;
private boolean won = true;
private boolean filled = false;
@Override
public void start(Stage primaryStage) {
theObject = this;
GridPane gridPane = new GridPane();
button = new Button[col][row];
for(int i = 0; i <col-1; i++) {
for(int j = 0; j <row-1; j++) {
button[i][j] = new Button();
button[i][j].setPrefSize(50, 50);
button[i][j].setOnAction(this);
gridPane.add(button[i][j], i ,j);
}
}
Scene scene = new Scene(gridPane);
primaryStage.setScene(scene);
primaryStage.show();
}
public void handle(ActionEvent e) {
Button b = (Button)e.getSource();
int c = findCol(b);
int r = findRow(b);
setTO(b,c);
System.out.println(c);
System.out.println(r);
}
public int findCol(Button b) {
int c = GridPane.getColumnIndex(b);
return c;
}
public int findRow(Button b) {
int r = GridPane.getRowIndex(b);
return r;
}
public void setTO(Button b,int c) {
for(int r = row -1; r >= 0; r--) {
if(button[c][r].getText().isEmpty()){
button[c][r].setText("x");
}
}
}
public void testButton(Button b) {
button[2][3].setText("2,3");
button[1][0].setText("1,0");
button[0][1].setText("0,1");
}
public static void main(String[] args) {
Application.launch(args);
}
}
Explanation / Answer
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.BorderPane; import javafx.concurrent.Task; import javafx.event.EventHandler; import javafx.event.ActionEvent; public class TootAndOtto extends Application implements EventHandler{ private static TootAndOtto theObject; private int row = 6; private int col = 6; private Button[][] button = new Button[col][row]; private boolean nextT = false; private boolean clickMade = true; private boolean won = true; private boolean filled = false; @Override public void start(Stage primaryStage) { theObject = this; GridPane gridPane = new GridPane(); button = new Button[col][row]; for(int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.