gpt4 book ai didi

java - 如何在 FXML 应用程序中主类和 Controller 类之间进行通信

转载 作者:行者123 更新时间:2023-11-30 03:05:14 28 4
gpt4 key购买 nike

我想在主类和 Controller 类之间通信阶段,这样我就可以使我的阶段可以从 Controller 类中的代码中拖动。最有效的方法是什么?

Main.java:

package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

import javafx.stage.StageStyle;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Main extends Application {

public Stage stage;
@Override
public void start(Stage primaryStage) throws Exception{
stage = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("WordToday");
Scene scene = new Scene(root, 300, 200);
stage.setScene(scene);
stage.setX(5);
stage.show();

//FileReader reader = new FileReader("C:\\Users\\Snipester\\IdeaProjects\\WordToday\\src\\sample\\Words.json");
//JSONObject jsonObj = (JSONObject) new JSONParser().parse(reader);
//JSONArray jsonArray = (JSONArray) jsonObj.get("Gre");
//List<Map<String, String>> list = jsonArray;
//System.out.println(list.get(0).get("word"));

}


public static void main(String[] args) {
launch(args);
}
}

Controller .java:

package sample;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class Controller{


public Button exitButton;
public ToolBar titleBar;
private double x, y;


//exit button
public void exitButtonClicked() {
Platform.exit();
}

//mouse pressed
public void MouseClicked(MouseEvent event){
//x = event.getSceneX();
//y = event.getSceneY();
}

//mouse dragged
public void MouseDragged(MouseEvent event){
// stage.setX(event.getScreenX()-x);
//stage.setY(event.getScreenY()-y);

}

}

FXML:

 <ToolBar fx:id="titleBar"
prefHeight="20.0"
prefWidth="600.0"
GridPane.rowIndex="0"
onMouseClicked="#MouseClicked"
onMouseDragged="#MouseDragged"
/>

最佳答案

您可以在任何节点上使用 getScene()getScene().getWindow():

//mouse pressed
public void MouseClicked(MouseEvent event){
double x = event.getSceneX();
double y = event.getSceneY();
Scene scene = titleBar.getScene();
Window window = scene.getWindow();
// etc...
}

关于java - 如何在 FXML 应用程序中主类和 Controller 类之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34976069/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com