此代码:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
primaryStage.setTitle("Load an Image");
primaryStage.setScene(new Scene(root));
BorderPane mainBorderPane = (BorderPane) primaryStage.getScene().lookup("#mainBorderPane");
mainBorderPane.setPadding(new Insets(8));
HBox controls = new HBox();
Button loadBtn = new Button("Load Image");
Button sobelEdgeDetectionBtn = new Button("Sobel Edge Detection");
loadBtn.setMaxWidth(Double.MAX_VALUE);
sobelEdgeDetectionBtn.setMaxWidth(Double.MAX_VALUE);
setBrowseFileAction(loadBtn);
controls.setSpacing(8);
controls.getChildren().addAll(loadBtn,sobelEdgeDetectionBtn);
mainBorderPane.setBottom(controls);
primaryStage.sizeToScene();
primaryStage.show();
}
private void setBrowseFileAction(Button loadBtn) {
loadBtn.setOnAction((event) -> {
Object source = event.getSource();
Scene scene = ((Node) source).getScene();
Stage stageOfEvent = (Stage) ((Node) source).getScene().getWindow();
BorderPane mainBorderPane = (BorderPane) scene.lookup("#mainBorderPane");
ImageView imageView = new ImageView();
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("JPG","*.jpg"),
new FileChooser.ExtensionFilter("JPEG","*.jpeg")
);
fileChooser.setTitle("Choose file...");
fileChooser.setInitialDirectory(
new File(System.getProperty("user.home"))
);
File file = fileChooser.showOpenDialog(stageOfEvent);
if(file != null) {
Image image = new Image("file:"+file.getAbsolutePath());
imageView.setImage(image);
mainBorderPane.setCenter(imageView);
stageOfEvent.sizeToScene();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
main.fxml文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<BorderPane id="mainBorderPane" />
..没有做我想做的事。
我想加载图片然后调整窗口大小并将其居中在屏幕上,无论图像大小如何。
花了太多时间。任何简单的快速解决方我可以通过添加大量代码来实现,我确信JavaFX的糟糕文档已经有了一个可以实现我想要的方法。
答案 0 :(得分:1)
在setBrowseFileAction的if语句末尾添加:
stageOfEvent.setWidth(image.getWidth()+40);
stageOfEvent.setHeight(image.getHeight()+40);