英文:
Change the property of a rectangle by using another class JavaFX
问题
我正在研究一个项目,我想在按下按钮时出现一个矩形。然而,我想通过将按钮点击导向不同的类来实现这一点。以下是我尝试过的内容:
这是我的第一个类,"Main"
static boolean btnClicked = false;
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Make Popup Visible");
Rectangle menu = new Rectangle(40, 40, 200, 200);
menu.setFill(Color.BLACK);
menu.setOpacity(0);
btn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
AddRect.showMenu();
});
if (btnClicked == true) {
menu.setOpacity(1);
}
Group root = new Group();
root.getChildren().addAll(btn, menu);
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
和我的第二个类,"AddRect"
public class AddRect {
static void showMenu() {
Main.btnClicked = true;
}
}
然而,这不起作用,我不知道为什么。有人能帮助我吗?我甚至不知道这是否是最好的方法(使用两个类),但如果有更好的方法,请告诉我。先谢谢!
[注意:以上是代码的翻译,不包括问题和其他内容。]
英文:
I'm working on a project and I want a rectangle to appear when I press a button. However, I want to do this by directing the button click to a different class. Here is what I've tried:
Here is my first class, "Main"
static boolean btnClicked = false;
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Make Popup Visible");
Rectangle menu = new Rectangle(40,40,200,200);
menu.setFill(Color.BLACK);
menu.setOpacity(0);
btn.addEventHandler(MouseEvent.MOUSE_CLICKED,(MouseEvent e) ->{
AddRect.showMenu();
});
if(btnClicked == true) {
menu.setOpacity(1);
}
Group root = new Group();
root.getChildren().addAll(btn, menu);
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
And my second class, "AddRect"
public class AddRect {
static void showMenu() {
Main.btnClicked = true;
}
}
However, this isn't working, and I don't know why. Can somebody help me? I don't even know if this is the best way to do it (Using two classes), but if there is a better way please let me know. Thanks in advance!
答案1
得分: 0
我明白了!我只需要将条件移到 EventHandler 内部
btn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
AddRect.showMenu();
if (btnClicked == true) {
menu.setOpacity(1);
}
});
英文:
I figured it out! I just had to move the conditional inside the EventHandler
btn.addEventHandler(MouseEvent.MOUSE_CLICKED,(MouseEvent e) ->{
AddRect.showMenu();
if(btnClicked == true) {
menu.setOpacity(1);
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论