2016-12-03 26 views
-1

當我試圖創建GUI計算器未修飾的階段。我添加了一個Hbox作爲標題欄,並給它一個onClicked/OnDragged方法來拖動主要的舞臺,但它似乎並不完美。因爲我怎麼能強迫光標停留在原地的窗口中拖動未修飾的舞臺

1)當我按下並開始拖動時,鼠標光標移動到窗口的左上角,你可以看到下面。我使用的方法是從這裏

X IMAGES:

When i click on middle of Hbox

Where the cursor moves when i start dragging

X這裏是我的主類

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一ND下面是我在我的控制器類中使用的方法來添加可拖動效果

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); 
} 
} 

如何拖動時我鎖定到位光標?

2)當我單擊是HBox中內部的接近/最小化按鈕,它也拖動窗口。有沒有辦法阻止?

回答

1

爲了方便整個窗口的移動,您需要兩個事件(按/拖動),當您按下欄時,動作開始,初始化位置(xOffset, yOffset),我認爲如果我沒有弄錯您所做的錯誤是,你所使用的屏幕,而不是場面這是解決你的第一個問題:對於第二個問題

//Use Press Event instead of Click Event 
xOffset = event.getSceneX(); 
yOffset = event.getSceneY(); 

//Drag Event 
window.setX(event.getScreenX() - xOffset); 
window.setY(event.getScreenY() - yOffset); 

,你可以佈局,這是外線添加關閉按鈕我是最簡單的解決方案。