In some of my applications I often need to center something horizontally or vertically within a larger space. Tired of writing this over and over I resolved to build a reusable layout class once and for all. Most importantly, this center layout is dynamic, meaning it will automatically do the right thing if the size of the nodes change, or if the size of the area you are centering in changes (say, by resizing the window). It even works if the contents are animated.
This is the code for CenterLayout.
Set/bind the width and height you want to center within, and
set the booleans to center horizontally or vertically (or both). If you have multiple nodes they will be stacked on
top of each other. If you want to center a column of nodes rather than having them stacked, then put them in a VBox{} and center that instead.
package centerlayout;
import javafx.scene.*;
/**
* @author joshua.marinacci@sun.com
*/
public class CenterLayout extends CustomNode {
public-init var centerVertical:Boolean = false;
public-init var centerHorizontal:Boolean = false;
public var width = 200.0 on replace { doLayout(); }
public var height = 200.0 on replace { doLayout(); }
public var content:Node[] on replace { doLayout(); }
var layoutNodes:Node[];
function doLayout() {
layoutNodes = for(node in content) {
var g = Group { content: node
translateX: bind if(centerHorizontal) {
(width - node.boundsInLocal.width) / 2
} else { 0 }
translateY: bind if(centerVertical) {
(height - node.boundsInLocal.height) / 2
} else { 0 }
};
g;
}
}
override public function create():Node {
return Group {
content: bind layoutNodes;
}
}
}
No comments:
Post a Comment