How to set maximum levels for treeItems in a tree (SWT)? - swt

I have an Tree and a button to add treeItems in each treeItem, sow how can I prevent user to make more then 2 level of treeItems on a tree in SWT?

Found solution:
private int getLevelOfItem(TreeItem item)
{
int counter = 0;
while(item.getParentItem() != null)
{
item = item.getParentItem();
counter++;
}
return counter;
}

Related

Find all children with different tags -Unity

I'm trying to get a number of all children with a certain tag from the parent object.
For example if a parent object has 20 children and their tags can switch between two tags, I would want to find out how many have either tag.
I want to do it on a mouse click. I've tried using transform.childCount and FindGameObjectsWithTag() however I'm not having any luck.
Any suggestions or pointers?
public static class Extensions {
public static int ChildCountWithTag(this Transform tr, string tag, bool checkInactive = false) {
int count = 0;
Transform [] trs = tr.GetComponentsInChildren<Transform>(checkInactive);
foreach(Transform t in trs) {
if(t.gameObject.CompareTag(tag) == true) { count++; }
}
return count;
}
}
Then you call it as:
void Start() {
int result = this.transform.ChildCountWithTag("Tag");
int resultB = this.transform.ChildCountWithTag("OtherTag", true);
}
The first returns how many active with the given tag "Tag", the second how many children with the tag "OtherTag", including inactive ones.

How to hide tab pages in a tab control

I am learner in c# and I have a small doubt.
In my windows form page, I have a tabControl contains 3 tabPages.I also have a comboBox outside the tabControl with 3 items listing the names of tab pages.
What i want to do is select the name of the first tabPage from the comboBox, and only that tabPage should be displayed by hiding the other tabPages.
Visibility property is not applicable to tabPages. So how can i do this?
Thanks in advance.
According to Hiding and Showing Tabpages in a Tabcontrol by Debasmit Samal:
Visiblity property has not been implemented on the TabControl, and
there is no Insert method also. Some workaround on this
private void HideTabPage(TabPage tp)
{
if (tabControl1.TabPages.Contains(tp))
tabControl1.TabPages.Remove(tp);
}
private void ShowTabPage(TabPage tp)
{
ShowTabPage(tp, tabControl1.TabPages.Count);
}
private void ShowTabPage(TabPage tp , int index)
{
if (tabControl1.TabPages.Contains(tp)) return;
InsertTabPage(tp, index);
}
private void InsertTabPage(TabPage tabpage, int index)
{
if (index < 0 || index > tabControl1.TabCount)
throw new ArgumentException("Index out of Range.");
tabControl1.TabPages.Add(tabpage);
if (index < tabControl1.TabCount - 1)
do
{
SwapTabPages(tabpage, (tabControl1.TabPages[tabControl1.TabPages.IndexOf(tabpage) - 1]));
}
while (tabControl1.TabPages.IndexOf(tabpage) != index);
tabControl1.SelectedTab = tabpage;
}
private void SwapTabPages(TabPage tp1, TabPage tp2)
{
if (tabControl1.TabPages.Contains(tp1) == false || tabControl1.TabPages.Contains(tp2) == false)
throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");
int Index1 = tabControl1.TabPages.IndexOf(tp1);
int Index2 = tabControl1.TabPages.IndexOf(tp2);
tabControl1.TabPages[Index1] = tp2;
tabControl1.TabPages[Index2] = tp1;
//Uncomment the following section to overcome bugs in the Compact Framework
//tabControl1.SelectedIndex = tabControl1.SelectedIndex;
//string tp1Text, tp2Text;
//tp1Text = tp1.Text;
//tp2Text = tp2.Text;
//tp1.Text=tp2Text;
//tp2.Text=tp1Text;
}

dynamically select a checkbox for siblings treenode in Smart GWT

I have a selectable Tree with checkbox appearance. I need to select all sibling TreeNode on selection of a specific TreeNode.
I could get all the sibling tree nodes, but I don't know what is the attribute name of TreeNode to make that checkbox selected.
Can anybody help me giving some way to select those nodes.
compareGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
#Override
public void onSelectionChanged(SelectionEvent event) {
TreeNode node = (TreeNode) event.getSelectedRecord();
TreeNode parent = tree.getParent(node);//tree is Tree object
treeGrid.selectRecord(parent);
TreeNode[] nodes = tree.getAllNodes(parent);
for(int i=0; i< nodes.length; i++){
if(!nodes[i].getAttributeAsBoolean("isSelected"))
treeGrid.selectRecord(nodes[i]);
}
}
}
});
You can use any of the following:
treeGrid.selectAllRecords();
treeGrid.selectRecord(record);
treeGrid.selectRecords(records);
The first method will select all the TreeNodes of the tree.
The 2nd one will select only one specified TreeNodes of the tree.
And the 3rd one will select multiple specified TreeNodes of the tree.
There are multiple overloaded methods for the last 2 methods, which allows you to specify Nodes in terms of, TreeNode(s) itself, or index of the TreeNode(s).
Here's a solution quite close (without checkboxes) to what you need.
employeeTreeGrid.addNodeClickHandler(new NodeClickHandler() {
public void onNodeClick(NodeClickEvent event) {
if (event.getNode() != null) {
TreeNode node = event.getNode();
TreeNode parent = employeeTree.getParent(node);
if (employeeTreeGrid.isSelected(node)) {
List<TreeNode> nodesToSelect = new ArrayList<TreeNode>();
// omit parent (root) if on first level
if (!"1".equals(node.getAttribute("ReportsTo"))) {
nodesToSelect.add(parent);
}
TreeNode[] siblings = employeeTree.getChildren(parent);
nodesToSelect.addAll(Arrays.asList(siblings));
RecordList recordList = employeeTreeGrid.getOriginalRecordList();
for (TreeNode treeNode : nodesToSelect) {
Record record = recordList.find("EmployeeId", treeNode.getAttribute("EmployeeId"));
if (record != null) {
employeeTreeGrid.selectRecord(record);
}
}
}
}
}
});
Have to use the RecordList and first find required records in order to use ListGrid.selectRecord() methods.
Using SelectionAppearance.CHECKBOX and SelectionChangedHandler can be tricky as programmatic selections are going to trigger further selection events.
This is based on Checkbox tree sample with below changes.
// employeeTreeGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
// employeeTreeGrid.setShowSelectedStyle(false);
employeeTreeGrid.setShowPartialSelection(false);
// employeeTreeGrid.setCascadeSelection(true);
employeeTreeGrid.setSelectionType(SelectionStyle.SIMPLE);
To get the value of selected checkbox from tree grid in smart gwt I have following solution ListGridRecord[] arrRec = event.getSelection(); sample code is below.
employeeTreeGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
employeeTreeGrid.setSelectionType(SelectionStyle.SIMPLE);
employeeTreeGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
#Override
public void onSelectionChanged(SelectionEvent event)
//selectedCounties Set to add selected checkbox or deslected checkbox names/title
if (selectedCounties == null || selectedCounties.size() == 0)
selectedCounties = new TreeSet<String>();
selectedCounties.clear();
ListGridRecord[] arrRec = event.getSelection();
for (ListGridRecord listGridRecord : arrRec) {
selectedCounties.add(listGridRecord.getAttribute("Name"));
}
// You can do iteration over it if needed
selectedCounties.remove("All Counties");
Iterator<String> it = selectedCounties.iterator();
while (it.hasNext()) {
if (it.next().contains("Zone")) {
it.remove();
}
}
}
});

GWT CellTable getVisibleRange() is not what i except

GWT2.4, CellTable with SimplePager, every page show 5 items(rows), suppose i have 8 items totally, at the first page i can see [1-5], when i press next, it will show [4-8] ( getVisibleRange() is [4-8]), i want it to show [6-8], Is there any way i can achieve this?
Thanks in advance.
Try setting
setRangeLimited(false)
with SimplePager
Or you can also override
#Override
public void setPageStart(int index) {
if (getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
// Removed the min to show fixed ranges
//if (isRangeLimited && display.isRowCountExact()) {
// index = Math.min(index, display.getRowCount() - pageSize);
//}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}

GWT: Select a TreeItem with right click

I'm capturing a right click event to show a context menu. What I haven't been able to figure out, is how to make the right click actually select the TreeItem, prior to showing of context menu.
All help is appreciated.
private Tree tree = new Tree() {
#Override
public void onBrowserEvent(Event event) {
if (event.getTypeInt() == Event.ONCONTEXTMENU) {
DOM.eventPreventDefault(event);
showContextMenu(event);
}
super.onBrowserEvent(event);
}
#Override
protected void setElement(Element elem) {
super.setElement(elem);
sinkEvents(Event.ONCONTEXTMENU);
}
};
ONMOUSEDOWN event gets fired before ONCONTEXTMENU. Have you tried to listen for onMouseDown events, and set the selected item? Something along these lines:
#Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (DOM.eventGetButton(event) == Event.BUTTON_RIGHT) {
TreeItem selectedItem = findSelectedItem(event);
if (selectedItem != null) {
selectedItem.setSelected(true);
}
} else {
super.onBrowserEvent(event);
}
break;
case Event.ONCONTEXTMENU:
showContextMenu(event);
break;
default:
super.onBrowserEvent(event);
break;
}
and findSelectedItem traverses the tree looking for the selected item:
TreeItem findSelectedItem(Event e) {
return findSelectedItemRecursive(event.getClientX(), event.getClientY());
}
TreeItem findSelectedTreeItemRecursive(TreeItem root, int x, int y) {
if (null == root) {
int count = getItemCount();
for (int i = 0; i < count; i++) {
TreeItem selected = findSelectedTreeItemRecursive(getItem(i), x, y);
if (selected != null) {
return selected;
}
}
return null;
}
int count = item.getChildCount();
for (int i = 0; i < count; i++) {
TreeItem selected = findSelectedTreeItem(item.getChild(i), x, y);
if (selected != null) {
return selected;
}
}
if (x >= item.getAbsoluteLeft()
&& x <= item.getAbsoluteLeft() + item.getOffsetWidth()
&& y >= item.getAbsoluteTop()
&& y <= item.getAbsoluteTop() + item.getOffsetHeight()) {
return item;
}
return null;
}
You can use dedicated overloaded TreeItem :
public class MyTreeItem extends TreeItem implements ContextMenuHandler {
public SBTreeItem(SBItemTree tree, String name) {
super();
Label w = new Label(name);
w.addDomHandler(this, ContextMenuEvent.getType());
setWidget(w);
}
public void onContextMenu(ContextMenuEvent event) {
Window.alert(getSBItem().getName());
event.getNativeEvent().stopPropagation();
}
}
I'd just like to add a couple of links leading to issues about this:
http://code.google.com/p/google-web-toolkit/issues/detail?id=4529&q=right%20click%20selection
http://code.google.com/p/google-web-toolkit/issues/detail?id=4604&q=right%20click%20selection
I know this is an old question, but hopefully here's an answer that will save time for the masses hitting this page from a Google search. IMO, the best way is to use Google's own internal tree searching code -- it's a solution that scales very well with the number of elements in the tree. I
am using GWT 2.5.1.
private void initTree() {
tree = new Tree() {
#Override
public void onBrowserEvent(Event event) {
/*
* If the event is a context menu event, we want the tree item
* to also be selected.
*
* This logic must occur before the call to the superclass
* method so the selection is updated before the context menu
* logic executes. This is useful when we want to make items in
* the context menu invisible/disabled based on the selection.
*/
if (DOM.eventGetType(event) == Event.ONCONTEXTMENU) {
if (getItemCount() > 0) {
// In my use case there is only 1 top-level tree item
TreeItem root = getItem(0);
// Taken from com.google.gwt.user.client.ui.Tree.elementClicked(Element):
ArrayList<Element> chain = new ArrayList<Element>();
collectElementChain(chain, getElement(), DOM.eventGetTarget(event));
TreeItem selection = findItemByChain(chain, 0, root);
/*
* For some reason SelectionEvent will only fire if
* selection is non-null; I am firing the selection
* event manually because I want to know when there has
* been a deselection of an item in the tree.
*/
if (selection != null) {
this.setSelectedItem(selection);
} else {
SelectionEvent.fire(this, null);
}
}
}
super.onBrowserEvent(event);
}
};
tree.setAnimationEnabled(true);
}
//// BEGIN code copied from com.google.gwt.user.client.ui.Tree:
/**
* Collects parents going up the element tree, terminated at the tree root.
*/
private void collectElementChain(ArrayList<Element> chain, Element hRoot,
Element hElem) {
if ((hElem == null) || (hElem == hRoot)) {
return;
}
collectElementChain(chain, hRoot, DOM.getParent(hElem));
chain.add(hElem);
}
private TreeItem findItemByChain(ArrayList<Element> chain, int idx,
TreeItem root) {
if (idx == chain.size()) {
return root;
}
Element hCurElem = chain.get(idx);
for (int i = 0, n = root.getChildCount(); i < n; ++i) {
TreeItem child = root.getChild(i);
if (child.getElement() == hCurElem) {
TreeItem retItem = findItemByChain(chain, idx + 1,
root.getChild(i));
if (retItem == null) {
return child;
}
return retItem;
}
}
return findItemByChain(chain, idx + 1, root);
}
//// END