我想在主类和控制器类之间进行通信,这样我就可以从控制器类的代码中使我的舞台可拖动了。最有效的方法是什么?
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"
/>
答案 0 :(得分:2)
您可以在任何节点上使用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...
}