我只是在学习JavaFX而且我正在尝试创建一个自定义标题栏,你可以像普通的那样移动,但是我没有使用移动代码本身,而是操纵窗口。
我正在使用 FXML 来管理布局BTW。
这是我的代码:
主要课程
public class Main extends Application {
public Stage mainStage;
@FXML
Parent root;
@Override
public void start(Stage primaryStage) {
this.mainStage = primaryStage;
try {
root = FXMLLoader.load(getClass().getResource("Main.fxml"));
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("Main.css").toString());
mainStage.initStyle(StageStyle.TRANSPARENT);
mainStage.setScene(scene);
mainStage.sizeToScene();
mainStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
控制器类
public class MainController {
@FXML
Parent root;
double startX;
double startY;
public void exit() {
System.exit(0);
}
@FXML
public void mousePressed(MouseEvent e) {
System.out.println("Initial:" + e.getX() + "," + e.getY()); //Debug code
startX = e.getSceneX();
startY = e.getSceneY();
}
@FXML
public void mouseDragged(MouseEvent e) {
System.out.println("Dragged:" + (e.getScreenX() - startX) + "," + (e.getScreenY() - startY)); //Debug code
if (e.getButton() == MouseButton.PRIMARY) {
Stage stage = (Stage) root.getScene().getWindow();
stage.setX(e.getScreenX() - startX);
stage.setY(e.getScreenY() - startY);
}
}
}
FXML
<fx:root prefHeight="633.0" prefWidth="1071.0" type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.franga2000.launcher.MainController">
<children>
<Pane onMouseDragged="#mouseDragged" onMousePressed="#mousePressed" prefHeight="43.0" prefWidth="1071.0" styleClass="titlebar" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Button layoutX="1019.0" layoutY="9.0" onMouseClicked="#exit" text="Quit" />
</children>
</Pane>
</children>
</fx:root>
即使我尝试修改mainStage
方法之外的主类中的start()
,我总是会遇到同样的崩溃:
Thread [JavaFX Application Thread] (Suspended (exception RuntimeException))
GlassViewEventHandler$MouseEventNotification.run() line: not available [local variables unavailable]
GlassViewEventHandler$MouseEventNotification.run() line: not available
AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]
GlassViewEventHandler.handleMouseEvent(View, long, int, int, int, int, int, int, int, int, boolean, boolean) line: not available
WinView(View).handleMouseEvent(long, int, int, int, int, int, int, int, int, boolean, boolean) line: not available
WinView(View).notifyMouse(int, int, int, int, int, int, int, boolean, boolean) line: not available
WinApplication._runLoop(String[], Launchable) line: not available [native method]
WinApplication.access$100(WinApplication, String[], Launchable) line: not available
WinApplication$3$1.run() line: not available
Thread.run() line: not available