我有一个未修饰的阶段,我添加了一个包含两个AnchorPains(一个标题栏和一个mainContent)的AnchorPane。为了像普通窗口一样使用这个窗口,我实现了p.e.用于在侧面调整大小并在标题栏上拖动它的功能。为了拖动窗口,我分析了MouseMvents onMouseDragged和onMousePressed(参见下面的源代码)。源代码基本上是可行的。但我有一个问题,如果我移动鼠标太快,窗口将不会移动。一开始,鼠标位于标题栏上。在此之后我将鼠标移动到一侧太快,因此它在窗口外面并且不再被拖动。一旦我回到标题栏,我就可以再次移动它。有没有人建议如何解决这个问题?是否可以将窗口绑定到鼠标光标?
这是我的源代码:
titleContent.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
Stage stage = (Stage) titleContent.getScene().getWindow();
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
if (mouseEvent.getClickCount()==1){
// record a delta distance for the drag and drop operation.
if (stage.getWidth()==bounds.getMaxX() && stage.getHeight()==bounds.getMaxY()){
wasMaximized =true;
}
if(!wasMaximized){
dragDelta.x = stage.getX() - mouseEvent.getScreenX();
dragDelta.y = stage.getY() - mouseEvent.getScreenY();
}
else{
dragDelta.x=-1*minWidth/2;
dragDelta.y=0;
wasMaximized=false;
}
}
}
});
titleContent.setOnMouseDragged(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
Scene scene = (Scene) titleContent.getScene();
if (!(mouseEvent.getX() < border || mouseEvent.getX() > scene.getWidth() -border) && !(mouseEvent.getX() < border && mouseEvent.getY() > scene.getHeight() -border)){
Stage stage = (Stage) titleContent.getScene().getWindow();
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
if (stage.getWidth()==bounds.getMaxX() && stage.getHeight()==bounds.getMaxY()){
stage.setWidth(minWidth);
stage.setHeight(minHeight);
}
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
}
}
});
答案 0 :(得分:0)
我找到了解决方案。对于每个人,如何对它感兴趣:问题是titlecontent.setOnMouseDragged函数中的if语句。如果鼠标在给定元素上被拖拽,则只调用该函数。这就是为什么没有必要在那里使用if语句。正确的功能如下:
titleContent.setOnMouseDragged(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
Scene scene = (Scene) titleContent.getScene();
if (!(mouseEvent.getX() < border || mouseEvent.getX() > scene.getWidth() -border) && !(mouseEvent.getX() < border && mouseEvent.getY() > scene.getHeight() -border)){
Stage stage = (Stage) titleContent.getScene().getWindow();
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
if (stage.getWidth()==bounds.getMaxX() && stage.getHeight()==bounds.getMaxY()){
stage.setWidth(minWidth);
stage.setHeight(minHeight);
}
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
}
}
因此,这是一个完整的解决方案,用于拖动和调整未修饰的舞台。希望它有所帮助。