我正在编写一个 javafx 应用程序,我想让我的窗口不超出屏幕边界,因为这没有多大用处。因此,例如,不应拖动窗口,使其一半超出屏幕。
public class ui extends Application{
public static void main (String[] args){
launch(args);
}
public void start(Stage mainStage){
mainStage.initStyle(StageStyle.DECORATED);
Rectangle2D mainScreen = Screen.getPrimary().getVisualBounds();
mainStage.setWidth(mainScreen.getWidth());
mainStage.setHeight(mainScreen.getHeight());
BorderPane mainPane = new BorderPane(background);
Scene mainScene = new Scene(mainPane, Color.BLACK);
mainStage.setScene(mainScene);
mainStage.show();
}
}
最佳答案
不这样做的原因有很多:您需要注意不要禁用用户可能期望的功能,例如在扩展桌面上拖动(即在多个物理显示器之间拖动)或在虚拟桌面之间移动窗口(例如 Mac OS X 中的“Spaces”,或 Linux 中的等效系统)。
您在这里可以做的最好的事情可能是用监听器观察窗口的位置,如果它超出了所需的范围,则将其推回最佳位置。作为用户体验,这可能有点不尽如人意,但实现了您想要的功能:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Rectangle2D;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class ConstrainedWindow extends Application {
@Override
public void start(Stage primaryStage) {
Bounds allScreenBounds = computeAllScreenBounds();
ChangeListener<Number> boundsListener = (obs, oldValue, newValue) -> {
double x = primaryStage.getX();
double y = primaryStage.getY();
double w = primaryStage.getWidth();
double h = primaryStage.getHeight();
if (x < allScreenBounds.getMinX()) {
primaryStage.setX(allScreenBounds.getMinX());
}
if (x + w > allScreenBounds.getMaxX()) {
primaryStage.setX(allScreenBounds.getMaxX() - w);
}
if (y < allScreenBounds.getMinY()) {
primaryStage.setY(allScreenBounds.getMinY());
}
if (y + h > allScreenBounds.getMaxY()) {
primaryStage.setY(allScreenBounds.getMaxY() - h);
}
};
primaryStage.xProperty().addListener(boundsListener);
primaryStage.yProperty().addListener(boundsListener);
primaryStage.widthProperty().addListener(boundsListener);
primaryStage.heightProperty().addListener(boundsListener);
primaryStage.show();
}
private Bounds computeAllScreenBounds() {
double minX = Double.POSITIVE_INFINITY ;
double minY = Double.POSITIVE_INFINITY ;
double maxX = Double.NEGATIVE_INFINITY ;
double maxY = Double.NEGATIVE_INFINITY ;
for (Screen screen : Screen.getScreens()) {
Rectangle2D screenBounds = screen.getBounds();
if (screenBounds.getMinX() < minX) {
minX = screenBounds.getMinX();
}
if (screenBounds.getMinY() < minY) {
minY = screenBounds.getMinY() ;
}
if (screenBounds.getMaxX() > maxX) {
maxX = screenBounds.getMaxX();
}
if (screenBounds.getMaxY() > maxY) {
maxY = screenBounds.getMaxY() ;
}
}
return new BoundingBox(minX, minY, maxX-minX, maxY-minY);
}
public static void main(String[] args) {
launch(args);
}
}
关于java - 将 javafx 窗口保持在屏幕边界内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203674/