我想在SplitPane中同步分频器,当分频器(0)移动时,我也希望通过分频器(1)进行相同的移动。我想我必须绑定divider(0)的positionProperty。
我怎样才能做到这一点?
答案 0 :(得分:0)
您需要将侦听器添加到每个分隔符的位置,并更新"链接的"分频器何时发生变化。确保您不会在无限递归循环中结束非常重要;最简单的方法是设置一个表示更新的标志,如果设置了更新,则不传播更新。
这是一个绑定两个分隔符的概念验证示例,因此它们之间的部分始终是分割窗格的1/3:
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.scene.control.SplitPane.Divider;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class SplitPaneDemo extends Application {
// helper class that binds two divider positions so the portion between them
// is always 1/3 of the split pane
private static class DividerPositionBinder {
private static final double ONE_THIRD = 1.0/3.0;
private boolean updating ;
DividerPositionBinder(List<Divider> dividers) {
dividers.get(0).positionProperty().addListener((obs, oldPos, newPos) -> {
// don't propagate update if already in an update:
if (updating) return ;
// special handling for right edge of split pane:
if (newPos.doubleValue() > 1.0 - ONE_THIRD) {
dividers.get(0).setPosition(1.0 - ONE_THIRD);
dividers.get(1).setPosition(1.0);
return ;
}
// make right divider the new value + 1/3:
updating = true ;
dividers.get(1).setPosition(newPos.doubleValue() + ONE_THIRD);
updating = false ;
});
dividers.get(1).positionProperty().addListener((obs, oldPos, newPos) -> {
// don't propagate update if already in an update:
if (updating) return ;
// special handling for left edge of split pane:
if (newPos.doubleValue() < ONE_THIRD) {
dividers.get(1).setPosition(ONE_THIRD);
dividers.get(0).setPosition(0.0);
return ;
}
// make left divider the new value - 1/3:
updating = true ;
dividers.get(0).setPosition(newPos.doubleValue() - ONE_THIRD);
updating = false ;
});
}
}
@Override
public void start(Stage primaryStage) {
Region left = new Pane();
left.setStyle("-fx-background-color: coral; ");
Region middle = new Pane();
middle.setStyle("-fx-background-color: aquamarine ;");
Region right = new Pane();
right.setStyle("-fx-background-color: cornflowerblue ;");
SplitPane splitPane = new SplitPane(left, middle, right);
new DividerPositionBinder(splitPane.getDividers());
Scene scene = new Scene(splitPane, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}