Java examples for JavaFX:Layout
Make a best attempt to replace the JavaFX original component with the replacement, and keep the same position and layout constraints in the container.
/*// www . ja va 2s.c om * Copyright 2013 Jason Winnebeck * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; public class Main { /** * Make a best attempt to replace the original component with the replacement, and keep the same * position and layout constraints in the container. * <p/> * Currently this method is probably not perfect. It uses three strategies: * <ol> * <li>If the original has any properties, move all of them to the replacement</li> * <li>If the parent of the original is a {@link BorderPane}, preserve the position</li> * <li>Preserve the order of the children in the parent's list</li> * </ol> * <p/> * This method does not transfer any handlers (mouse handlers for example). * * @param original non-null Node whose parent is a {@link Pane}. * @param replacement non-null Replacement Node */ public static void replaceComponent(Node original, Node replacement) { Pane parent = (Pane) original.getParent(); //transfer any properties (usually constraints) replacement.getProperties().putAll(original.getProperties()); original.getProperties().clear(); ObservableList<Node> children = parent.getChildren(); int originalIndex = children.indexOf(original); if (parent instanceof BorderPane) { BorderPane borderPane = (BorderPane) parent; if (borderPane.getTop() == original) { children.remove(original); borderPane.setTop(replacement); } else if (borderPane.getLeft() == original) { children.remove(original); borderPane.setLeft(replacement); } else if (borderPane.getCenter() == original) { children.remove(original); borderPane.setCenter(replacement); } else if (borderPane.getRight() == original) { children.remove(original); borderPane.setRight(replacement); } else if (borderPane.getBottom() == original) { children.remove(original); borderPane.setBottom(replacement); } } else { //Hope that preserving the properties and position in the list is sufficient children.set(originalIndex, replacement); } } }