我一直在尝试使用图形界面编写 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 类访问按钮。
最佳答案
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");
}
}
关于java - 从另一个类访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016521/