source: src/main/java/weka/gui/PropertySelectorDialog.java @ 22

Last change on this file since 22 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 8.2 KB
RevLine 
[4]1/*
2 *    This program is free software; you can redistribute it and/or modify
3 *    it under the terms of the GNU General Public License as published by
4 *    the Free Software Foundation; either version 2 of the License, or
5 *    (at your option) any later version.
6 *
7 *    This program is distributed in the hope that it will be useful,
8 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *    GNU General Public License for more details.
11 *
12 *    You should have received a copy of the GNU General Public License
13 *    along with this program; if not, write to the Free Software
14 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17/*
18 *    PropertySelectorDialog.java
19 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
20 *
21 */
22
23package weka.gui;
24
25import weka.experiment.PropertyNode;
26
27import java.awt.BorderLayout;
28import java.awt.Container;
29import java.awt.Frame;
30import java.awt.event.ActionEvent;
31import java.awt.event.ActionListener;
32import java.beans.BeanInfo;
33import java.beans.IntrospectionException;
34import java.beans.Introspector;
35import java.beans.PropertyDescriptor;
36import java.beans.PropertyEditor;
37import java.beans.PropertyEditorManager;
38import java.lang.reflect.InvocationTargetException;
39import java.lang.reflect.Method;
40
41import javax.swing.Box;
42import javax.swing.BoxLayout;
43import javax.swing.JButton;
44import javax.swing.JDialog;
45import javax.swing.JScrollPane;
46import javax.swing.JTree;
47import javax.swing.tree.DefaultMutableTreeNode;
48import javax.swing.tree.TreePath;
49import javax.swing.tree.TreeSelectionModel;
50
51/**
52 * Allows the user to select any (supported) property of an object, including
53 * properties that any of it's property values may have.
54 *
55 * @author Len Trigg (trigg@cs.waikato.ac.nz)
56 * @version $Revision: 1.9 $
57 */
58public class PropertySelectorDialog
59  extends JDialog {
60
61  /** for serialization */
62  private static final long serialVersionUID = -3155058124137930518L;
63 
64  /** Click to choose the currently selected property */
65  protected JButton m_SelectBut = new JButton("Select");
66
67  /** Click to cancel the property selection */
68  protected JButton m_CancelBut = new JButton("Cancel");
69
70  /** The root of the property tree */
71  protected DefaultMutableTreeNode m_Root;
72
73  /** The object at the root of the tree */
74  protected Object m_RootObject;
75
76  /** Whether the selection was made or cancelled */
77  protected int m_Result;
78
79  /** Stores the path to the selected property */
80  protected Object [] m_ResultPath;
81
82  /** The component displaying the property tree */
83  protected JTree m_Tree;
84
85  /** Signifies an OK property selection */
86  public static final int APPROVE_OPTION = 0;
87
88  /** Signifies a cancelled property selection */
89  public static final int CANCEL_OPTION = 1;
90 
91  /**
92   * Create the property selection dialog.
93   *
94   * @param parentFrame the parent frame of the dialog
95   * @param rootObject the object containing properties to select from
96   */
97  public PropertySelectorDialog(Frame parentFrame, Object rootObject) {
98   
99    super(parentFrame, "Select a property", true);
100    m_CancelBut.addActionListener(new ActionListener() {
101      public void actionPerformed(ActionEvent e) {
102        m_Result = CANCEL_OPTION;
103        setVisible(false);
104      }
105    });
106    m_SelectBut.addActionListener(new ActionListener() {
107      public void actionPerformed(ActionEvent e) {
108        // value = path from root to selected;
109        TreePath tPath = m_Tree.getSelectionPath();
110        if (tPath == null) {
111          m_Result = CANCEL_OPTION;
112        } else {
113          m_ResultPath = tPath.getPath();
114          if ((m_ResultPath == null) || (m_ResultPath.length < 2)) {
115            m_Result = CANCEL_OPTION;
116          } else {
117            m_Result = APPROVE_OPTION;
118          }
119        } 
120        setVisible(false);
121      }
122    });
123    m_RootObject = rootObject;
124    m_Root = new DefaultMutableTreeNode(
125             new PropertyNode(m_RootObject));
126    createNodes(m_Root);
127   
128    Container c = getContentPane();
129    c.setLayout(new BorderLayout());
130    //    setBorder(BorderFactory.createTitledBorder("Select a property"));
131    Box b1 = new Box(BoxLayout.X_AXIS);
132    b1.add(m_SelectBut);
133    b1.add(Box.createHorizontalStrut(10));
134    b1.add(m_CancelBut);
135    c.add(b1, BorderLayout.SOUTH);
136    m_Tree = new JTree(m_Root);
137    m_Tree.getSelectionModel()
138      .setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
139    c.add(new JScrollPane(m_Tree), BorderLayout.CENTER);
140    pack();
141  }
142
143  /**
144   * Pops up the modal dialog and waits for cancel or a selection.
145   *
146   * @return either APPROVE_OPTION, or CANCEL_OPTION
147   */
148  public int showDialog() {
149
150    m_Result = CANCEL_OPTION;
151    setVisible(true);
152    return m_Result;
153  }
154
155  /**
156   * Gets the path of property nodes to the selected property.
157   *
158   * @return an array of PropertyNodes
159   */
160  public PropertyNode [] getPath() {
161
162    PropertyNode [] result = new PropertyNode [m_ResultPath.length - 1];
163    for (int i = 0; i < result.length; i++) {
164      result[i] = (PropertyNode) ((DefaultMutableTreeNode) m_ResultPath[i + 1])
165        .getUserObject();
166    }
167    return result;
168  }
169
170  /**
171   * Creates the property tree below the current node.
172   *
173   * @param localNode a value of type 'DefaultMutableTreeNode'
174   */
175  protected void createNodes(DefaultMutableTreeNode localNode) {
176
177    PropertyNode pNode = (PropertyNode)localNode.getUserObject();
178    Object localObject = pNode.value;
179    // Find all the properties of the object in the root node
180    PropertyDescriptor localProperties[];
181    try {
182      BeanInfo bi = Introspector.getBeanInfo(localObject.getClass());
183      localProperties = bi.getPropertyDescriptors();
184    } catch (IntrospectionException ex) {
185      System.err.println("PropertySelectorDialog: Couldn't introspect");
186      return;
187    }
188
189    // Put their values into child nodes.
190    for (int i = 0; i < localProperties.length; i++) {
191      // Don't display hidden or expert properties.
192      if (localProperties[i].isHidden() || localProperties[i].isExpert()) {
193        continue;
194      }
195      String name = localProperties[i].getDisplayName();
196      Class type = localProperties[i].getPropertyType();
197      Method getter = localProperties[i].getReadMethod();
198      Method setter = localProperties[i].getWriteMethod();
199      Object value = null;
200      // Only display read/write properties.
201      if (getter == null || setter == null) {
202        continue;
203      }
204      try {
205        Object args[] = { };
206        value = getter.invoke(localObject, args);
207        PropertyEditor editor = null;
208        Class pec = localProperties[i].getPropertyEditorClass();
209        if (pec != null) {
210          try {
211            editor = (PropertyEditor)pec.newInstance();
212          } catch (Exception ex) {
213          }
214        }
215        if (editor == null) {
216          editor = PropertyEditorManager.findEditor(type);
217        }
218        if ((editor == null) || (value == null)) {
219          continue;
220        }
221      } catch (InvocationTargetException ex) {
222        System.err.println("Skipping property " + name
223                           + " ; exception on target: "
224                           + ex.getTargetException());
225        ex.getTargetException().printStackTrace();
226        continue;
227      } catch (Exception ex) {
228        System.err.println("Skipping property " + name
229                           + " ; exception: " + ex);
230        ex.printStackTrace();
231        continue;
232      }
233      // Make a child node
234      DefaultMutableTreeNode child = new DefaultMutableTreeNode(
235                                     new PropertyNode(value,
236                                                      localProperties[i],
237                                                      localObject.getClass()));
238      localNode.add(child);
239      createNodes(child);
240    }
241  }
242
243 
244  /**
245   * Tests out the property selector from the command line.
246   *
247   * @param args ignored
248   */
249  public static void main(String [] args) {
250
251    try {
252      GenericObjectEditor.registerEditors();
253
254      Object rp
255        = new weka.experiment.AveragingResultProducer();
256      final PropertySelectorDialog jd = new PropertySelectorDialog(null, rp);
257      int result = jd.showDialog();
258      if (result == PropertySelectorDialog.APPROVE_OPTION) {
259        System.err.println("Property Selected");
260        PropertyNode [] path = jd.getPath();
261        for (int i = 0; i < path.length; i++) {
262          PropertyNode pn = path[i];
263          System.err.println("" + (i + 1) + "  " + pn.toString()
264                             + " " + pn.value.toString());
265        }
266      } else {
267        System.err.println("Cancelled");
268      }
269      System.exit(0);
270    } catch (Exception ex) {
271      ex.printStackTrace();
272      System.err.println(ex.getMessage());
273    }
274  }
275}
Note: See TracBrowser for help on using the repository browser.