1
我想在主類和控制器類之間進行通信階段,這樣我可以使階段可以從控制器類中的代碼拖放。什麼是最有效的方法來做到這一點?如何在FXML應用程序中的主類和控制器類之間進行通信階段
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"
/>
然後在舞臺上注入舞臺 – Elltz
'Controller controller = loader。 getController();' 使用此代碼,它工作。任何人都可以解釋此代碼? –
absolutezero