我一直在尝试使用图形界面对 TicTacToe 进行编码,以便更好地理解JavaFX。当我尝试从我的Graphics类访问 TicTacToe 类中的按钮和b1.setOnAction()
时出现问题。
public class Graphics extends Application {
@Override
public void start(Stage stage) {
GridPane gp = new GridPane();
Button b1 = new Button();
b1.setPrefSize(50, 50);
gp.add(b1, 2, 2);
Scene scene = new Scene(gp, 230, 250);
stage.setTitle("TicTacToe");
stage.setScene(scene);
stage.show();
}
}
如果我使用launch(args)实现一个main方法,那么它自己的图形工作并创建一个带有我需要的所有必要按钮的Windows。如果b1.setOnAction()
方法在此处,我也可以访问按钮。
public class TicTacToe {
public void game() {
// This doesnt work, it just visualizes my problem...
b1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
b1.setText("X");
}
});
}
}
在 TicTacToe 我希望随时访问所有按钮,但我不知道这是如何工作的。我试图谷歌我的问题,但没有答案可以修复我的代码。
(我尽量在代码中删除以简化操作。如果遗漏了重要内容,请告诉我,我会添加它。)
TL; DR 每当我想执行某个操作时,我想在我的 TicTacToe 类中访问我的Graphics类中的按钮。
答案 0 :(得分:2)
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Graphics extends Application {
private Button b1;
@Override
public void start(Stage stage) {
GridPane gp = new GridPane();
b1 = new Button();
b1.setPrefSize(50, 50);
gp.add(b1, 2, 2);
Scene scene = new Scene(gp, 230, 250);
stage.setTitle("TicTacToe");
stage.setScene(scene);
stage.show();
}
public Button getButton(){return b1;}
}
class TicTacToe {
Graphics g;
public TicTacToe() {
//If you don't want to create Graphics here, get a reference to it
g = new Graphics();
}
public void game() {
g.getButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//do what you need
}
});
}
}
修改:我不确定您要做什么,但您可能希望Graphics
构建TicTacToe
:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Graphics extends Application {
public Graphics() {
new TicTacToe(this);
}
private Button b1;
@Override
public void start(Stage stage) {
GridPane gp = new GridPane();
b1 = new Button();
b1.setPrefSize(50, 50);
gp.add(b1, 2, 2);
Scene scene = new Scene(gp, 230, 250);
stage.setTitle("TicTacToe");
stage.setScene(scene);
stage.show();
}
public Button getButton(){return b1;}
public static void main(String[] args) {
launch(args);
}
}
class TicTacToe {
Graphics g;
public TicTacToe(Graphics g) {
this.g = g;
}
public void game() {
/**
g.getButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//do what you need
}
});*/
//if you wan to set buttons text :
g.getButton().setText("X");
}
}