我想要做的是如果调整场景的大小(应用程序的窗口),我想相应地调整窗口内的内容。我已经发布了我迄今为止所做的代码
装载程序类
public class ResizingButtons extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
scene.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
try{
System.out.println("Scene Width Property is " + scene.getWidth());
}
catch(Exception e){
System.out.println("Error in width listener of scene" +e.getMessage());
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
这是FXMLDocument.fxml fxml类的控制器
public class FXMLDocumentController implements Initializable {
@FXML
public Button btn1;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void changeBtnSize(){
btn1.setPrefHeight(200);
btn1.setStyle("-fx-background-color:red");
}
}
当调整窗口大小时,我想访问控制器类的changeBtnSize()方法。
答案 0 :(得分:1)
您可以从FXMLLoader
获取控制器实例。像这样重构您的代码:
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml")); // Use loader instance
Parent root = loader.load();
FXMLDocumentController controller = loader.getController(); // Now you have controller refference here
//add your listener, feel free to use your controller inside listener implementation
}