Move Up/Down a Widget in Visual Library API

Let’s say I’m building a Scene and adding some LayerWidgets. Next I want to let user to arrange the order of these LayerWidgets, just like any other Layer-like functionality in Photoshop or CorelDraw. Bring forward, bring backward, bring to front, and bring to back.

Yay bringToFront and bringToBack is already there! Now it’s time to see their code and use our copy-paste-modify wizard. I’ll start from bringToFront to create a bring-forward function that is bringUp.

Applying C.bringToFront to an array of children (last children on the front)

A-B-C-D-E

will result

A-B-D-E-C

On the other hand, I want my C.bringUp to rearrange

A-B-C-D-E

into

A-B-D-C-E

Thanks to private Widget parentWidget AND private List children, I can’t imitate the code of bringToFront to my bringUp function. OK, it’s time to improvise.

Note that the expected result of D.bringUp can be acquired using a chain of D.bringToFront-B.bringToFront-A.bringToFront. So here it is my implementation of bringUp :

//reference to itsParent.children
List<Widget> children = this.getParentWidget().getChildren();
int size = children.size();
int movedIdx = children.indexOf(this);
if (movedIdx == size - 1) {
	//already on top
} else if (2 * (movedIdx + 1) < size) {
	//too far to the start of the list 
	//use bringDown of its next sibling
	children.get(movedIdx + 1).bringToBack();
	if (movedIdx > 1) {
		for (int j = 0; j < movedIdx; j++) {
			children.get(movedIdx).bringToBack();
		}
	}
} else {
	children.get(movedIdx).bringToFront();
	if (movedIdx < size - 2) {
		for (int j = 0; j < size - movedIdx - 2; j++) {
			children.get(movedIdx + 1).bringToFront();
		}
	}
}

This code is tested. We can then implement bringDown method analogously.

This entry was posted in netbeans platform, visual library api. Bookmark the permalink.

Comments are closed.