我有以下问题:
我在分辨率为 Full HD 的桌面上创建了一个 JavaFX
窗口,并设置场景如下:
Scene scene = new Scene(root,1475,1015);
当我在分辨率为
1360*760
的笔记本电脑上运行应用程序时,我无法看到整个应用程序,也无法调整大小。如何设置我的应用程序根据桌面/笔记本电脑的分辨率和尺寸自动调整大小?
我有以下问题:
我在分辨率为 Full HD 的桌面上创建了一个 JavaFX
窗口,并设置场景如下:
Scene scene = new Scene(root,1475,1015);
1360*760
的笔记本电脑上运行应用程序时,我无法看到整个应用程序,也无法调整大小。我相信您正在寻找这个
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
这将允许您使用设备的屏幕尺寸,调整大小只需要使程序中对象的长度/宽度与屏幕的宽度和高度成比例。
请注意:
您必须使用JavaFX中内置的布局(BorderPane、GridPane等)
这不能自动完成。您必须编写程序来实现它。
例如,通常情况下您想要知道不包含任务栏的屏幕宽度或高度(在Windows、Linux、Mac、Solaris中)。在这种情况下,您可以使用 getVisualBounds()...
主题
您正在询问响应式设计。以下是一个示例,展示了您想要创建的内容。虽然这不是最佳解决方案,但我意思是它可以修改以提高性能(如果是StageStyle.UNDECORATED
,我还添加了一些代码以移动窗口,请拖动窗口查看此效果):
import javafx.application.Application;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class FX extends Application {
int screenWidth = (int) Screen.getPrimary().getBounds().getWidth();
int screenHeight = (int) Screen.getPrimary().getBounds().getHeight();
Stage stage;
Scene scene;
int initialX;
int initialY;
@Override
public void start(Stage s) throws Exception {
// root
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color:rgb(186,153,122,0.7); -fx-background-radius:30;");
// Responsive Design
int sceneWidth = 0;
int sceneHeight = 0;
if (screenWidth <= 800 && screenHeight <= 600) {
sceneWidth = 600;
sceneHeight = 350;
} else if (screenWidth <= 1280 && screenHeight <= 768) {
sceneWidth = 800;
sceneHeight = 450;
} else if (screenWidth <= 1920 && screenHeight <= 1080) {
sceneWidth = 1000;
sceneHeight = 650;
}
// Scene
stage = new Stage();
stage.initStyle(StageStyle.TRANSPARENT);
scene = new Scene(root, sceneWidth, sceneHeight, Color.TRANSPARENT);
// Moving
scene.setOnMousePressed(m -> {
if (m.getButton() == MouseButton.PRIMARY) {
scene.setCursor(Cursor.MOVE);
initialX = (int) (stage.getX() - m.getScreenX());
initialY = (int) (stage.getY() - m.getScreenY());
}
});
scene.setOnMouseDragged(m -> {
if (m.getButton() == MouseButton.PRIMARY) {
stage.setX(m.getScreenX() + initialX);
stage.setY(m.getScreenY() + initialY);
}
});
scene.setOnMouseReleased(m -> {
scene.setCursor(Cursor.DEFAULT);
});
stage.setScene(scene);
stage.show();
}
/**
* Main Method
*
* @param args
*/
public static void main(String[] args) {
launch(args);
}
}
primaryStage.setMaximized(true);
Scene scene = new Scene(root, Double.MAX_VALUE, Double.MAX_VALUE);
stage.SetMaximized(true)
将其设置为可用屏幕大小,尽管同时使用这两个答案可以使最小化时的应用程序看起来更整洁。 - Matt1-使用JavaFX布局(BorderPane、GridPane等等...)
2-添加一些布局限制
您可以使用Scene Builder生成FXML文件,并调整屏幕大小以查看发生了什么,请参见此教程layout
这是您告诉程序根据限制绘制组件的方法,因此,以这种方式它将是响应式设计,它会遵循您的约束并自动调整组件。