I'm trying to create gui calculator with an undecorated stage. I added an Hbox as the title bar and set gave it an onClicked/OnDragged methods to move the primary stage around when dragged, however it doesn't seem to work perfectly. because
1) When i press and start dragging, the mouse cursor moves to the top left corner of the window as you can see below. The method i used is from here
X IMAGES:
When i click on middle of Hbox
Where the cursor moves when i start dragging
X Here is my main class
public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene mainSCENE = new Scene(root); mainSCENE.getStylesheets().add(this.getClass().getResource("calculator.css").toExternalForm()); mainSCENE.setFill(Color.TRANSPARENT); primaryStage.initStyle(StageStyle.TRANSPARENT); primaryStage.setResizable(false); primaryStage.setScene(mainSCENE); mainWindow = primaryStage; primaryStage.show(); }
X and here are the methods i used in my Controller class to add the draggable effect
public class Controller { @FXML Circle btnCLOSE; @FXML Circle btnMINIMIZE; @FXML HBox hboxTitleBar; private double xOffset = 0; private double yOffset = 0; public void handle(MouseEvent event) throws IOException, LineUnavailableException, UnsupportedAudioFileException { // Plays click audio when buttons are clicked AudioInputStream audioIn = AudioSystem.getAudioInputStream(getClass().getResource("click.wav")); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); // Add functionality to minimize/close buttons btnCLOSE.addEventHandler(MouseEvent.MOUSE_CLICKED, event1 -> System.exit(0)); btnMINIMIZE.addEventHandler(MouseEvent.MOUSE_CLICKED, event1 -> Main.mainWindow.setIconified(true)); } // Makes the UNDECORATED window draggable from the title bar Hbox public void setOnClicked(MouseEvent event) { System.out.println("CLICKED"); xOffset = Main.mainWindow.getX() - event.getScreenX(); yOffset = Main.mainWindow.getY() - event.getScreenY(); } public void setOnDragged(MouseEvent event) { Main.mainWindow.setX(event.getScreenX() + xOffset); Main.mainWindow.setY(event.getScreenY() + yOffset); } }
How can i lock the cursor in place when dragging?
2) When i click the close/minimize buttons that are inside the HBox, it also drags the window. Is there a way to prevent that?