2017-02-24 36 views

回答

2

不,只有3种不同的调整大小行为。

  • NEVER
  • SOMETIMES
  • ALWAYS

NEVER显然不是你需要什么,你不能用剩下的2个调整优先让3个孩子在3种不同的方式。

您需要实现这种布局的自己:

public class HLayout extends Pane { 

    @Override 
    protected void layoutChildren() { 
     final double w = getWidth(); 
     final double h = getHeight(); 
     final double baselineOffset = getBaselineOffset(); 

     List<Node> managedChildren = getManagedChildren(); 
     int size = managedChildren.size(); 

     // compute minimal offsets from the left and the sum of prefered widths 
     double[] minLeft = new double[size]; 
     double pW = 0; 
     double s = 0; 
     for (int i = 0; i < size; i++) { 
      minLeft[i] = s; 
      Node child = managedChildren.get(i); 
      s += child.minWidth(h); 
      pW += child.prefWidth(h); 
     } 

     int i = size - 1; 
     double rightBound = Math.min(w, pW); 
     // use prefered sizes until constraint is reached 
     for (; i >= 0; i--) { 
      Node child = managedChildren.get(i); 
      double prefWidth = child.prefWidth(h); 
      double prefLeft = rightBound - prefWidth; 
      if (prefLeft >= minLeft[i]) { 
       layoutInArea(child, prefLeft, 0, prefWidth, h, baselineOffset, HPos.LEFT, VPos.TOP); 
       rightBound = prefLeft; 
      } else { 
       break; 
      } 
     } 
     // use sizes determined by constraints 
     for (; i >= 0; i--) { 
      double left = minLeft[i]; 
      layoutInArea(managedChildren.get(i), left, 0, rightBound-left, h, baselineOffset, HPos.LEFT, VPos.TOP); 
      rightBound = left; 
     } 
    } 

} 

请注意,你应该也覆盖计算PREF尺寸的实现。

使用例:

@Override 
public void start(Stage primaryStage) { 
    HLayout hLayout = new HLayout(); 

    // fills space required for window "buttons" 
    Region filler = new Region(); 
    filler.setMinWidth(100); 
    filler.setPrefWidth(100); 

    Label l1 = new Label("Hello world!"); 
    Label l2 = new Label("I am your father!"); 
    Label l3 = new Label("To be or not to be..."); 
    hLayout.getChildren().addAll(filler, l1, l2, l3); 

    Scene scene = new Scene(hLayout); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 
+0

很大,但如何改变它的aligment向左?我只是从0到1的迭代,但现在每个标签而不是最后一个缩短到“...”,不会改变什么是HLayout宽度。如何解决它? – MrKaszu

+0

@MKKAZZO这要求你限制最初的'rightBound'的儿童喜好宽度的总和。我编辑了答案。 – fabian