2016-05-04 34 views
0

我使用某些事件在HBox上放置小矩形。當窗口沒有被調整大小時,它們的位置是完美的,但是當你從小屏幕到全屏時,它們的位置是錯誤的(當然,因爲它們在放置時獲得了X的一定值 - 這通過獲得在特定時刻HBox的寬度)。HBox上的Java節點動態位置

問:

我怎樣才能使這些位置動態的,所以當我調整窗口的大小,他們留在比例是多少?

圖片: Normal view Fullscreen

代碼:

@FXML HBox tagLine; // initializes the HBox 

... 

public void addTag(String sort) { 
    Rectangle rect = new Rectangle(20, tagLine.getHeight()); 
    double pos = timeSlider.getValue()/100 * tagLine.getWidth(); // retrieves position at the moment of being called 
    rect.setTranslateX(pos); 
    rect.setOnMouseEntered(new EventHandler<MouseEvent>() { 
     @Override 
     public void handle(MouseEvent event) { 
      showNotification("Gemarkeerde gebeurtenis: " + sort); 
     } 
    }); 
    rect.setOnMouseExited(new EventHandler<MouseEvent>() { 
     @Override 
     public void handle(MouseEvent event) { 
      notificationHide.play(); 
     } 
    }); 

    tagLine.getChildren().add(rect); 
} 
+0

你如何定位在HBox中的矩形?保證金?把節點放在它的左邊? 'translateX'? – fabian

+0

您需要向我們展示一些代碼。只需編輯您的問題並添加您當前用於翻譯矩形的邏輯。 – ItachiUchiha

回答

1

,你需要考慮到在翻譯與負責大小形狀是你需要幾件事情:

  • 從其中心
  • 翻譯形狀如果翻譯依賴於節點的寬度,收聽該特定節點的到由具有變化和更改的翻譯屬性相應

上述兩點似乎都在您的實施中缺失。你永遠不會聽到HBox的寬度屬性。 pos的計算也不考慮矩形的中心。

下面是一個例子,試圖將矩形保持在中心位置,而不管您的HBox的大小是多少。

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.layout.HBox; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 

public class Main extends Application { 

    private static final int SIDE = 40; 
    private static final double DEFAULT_WIDTH = 200; 
    private static final double DEFAULT_POSITION = 100; 

    @Override 
    public void start(Stage primaryStage) { 

     Rectangle rectangle = new Rectangle(SIDE, SIDE); 
     HBox root = new HBox(rectangle); 
     root.setPrefWidth(DEFAULT_WIDTH); 

     rectangle.translateXProperty().bind(root.widthProperty().multiply(DEFAULT_POSITION/DEFAULT_WIDTH).subtract(SIDE/2)); 

     Scene scene = new Scene(root); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

enter image description here