View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.example.demo;
21  
22  import javax.enterprise.context.SessionScoped;
23  import javax.inject.Named;
24  import javax.swing.tree.DefaultMutableTreeNode;
25  import java.io.Serializable;
26  
27  @SessionScoped
28  @Named
29  public class TreeSelectController implements Serializable {
30  
31    private DefaultMutableTreeNode sample;
32    private String selectable = "multi";
33  
34    public TreeSelectController() {
35      sample = CategoryTree.createSample();
36    }
37  
38    public DefaultMutableTreeNode getSample() {
39      return sample;
40    }
41  
42    public String getSelectable() {
43      return selectable;
44    }
45  
46    public void setSelectable(final String selectable) {
47      this.selectable = selectable;
48      resetSelection(sample);
49    }
50  
51    public void resetSelection(final DefaultMutableTreeNode node) {
52      final Node userObject = (Node) node.getUserObject();
53      userObject.setSelected(false);
54      for (int i = 0; i < node.getChildCount(); i++) {
55        final DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
56        resetSelection(child);
57      }
58    }
59  
60    public String getSelectedNodes() {
61      final StringBuilder stringBuilder = new StringBuilder();
62      buildSelectedNodesString(stringBuilder, sample);
63      if (stringBuilder.length() > 2) {
64        return stringBuilder.substring(2); // Remove ', '.
65      } else {
66        return "";
67      }
68    }
69  
70    private void buildSelectedNodesString(final StringBuilder stringBuilder, final DefaultMutableTreeNode node) {
71      final Node userObject = (Node) node.getUserObject();
72      if (userObject.isSelected()) {
73        stringBuilder.append(", ");
74        stringBuilder.append(userObject.getName());
75      }
76      for (int i = 0; i < node.getChildCount(); i++) {
77        final DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
78        buildSelectedNodesString(stringBuilder, child);
79      }
80    }
81  }