genericobjecteditor.java

来自「Java 编写的多种数据挖掘算法 包括聚类、分类、预处理等」· Java 代码 · 共 1,764 行 · 第 1/4 页

JAVA
1,764
字号
        m_Backup = m_Object;        m_Object = c;        if (m_EditorComponent != null) {      m_EditorComponent.updateChildPropertySheet();    }    if (trueChange) {      m_Support.firePropertyChange("", null, null);    }  }    /**   * Gets the current Object.   *   * @return the current Object   */  public Object getValue() {    return m_Object;  }    /**   * Supposedly returns an initialization string to create a Object   * identical to the current one, including it's state, but this doesn't   * appear possible given that the initialization string isn't supposed to   * contain multiple statements.   *   * @return the java source code initialisation string   */  public String getJavaInitializationString() {    return "new " + m_Object.getClass().getName() + "()";  }  /**   * Returns true to indicate that we can paint a representation of the   * Object.   *   * @return true   */  public boolean isPaintable() {    return true;  }  /**   * Paints a representation of the current Object.   *   * @param gfx the graphics context to use   * @param box the area we are allowed to paint into   */  public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) {    if (m_Enabled) {      String rep;      if (m_Object != null) {	rep = m_Object.getClass().getName();      } else {	rep = "None";      }      int dotPos = rep.lastIndexOf('.');      if (dotPos != -1) {	rep = rep.substring(dotPos + 1);      }      /*      if (m_Object instanceof OptionHandler) {	rep += " " + Utils.joinOptions(((OptionHandler)m_Object)				       .getOptions());      }      */      java.awt.Font originalFont = gfx.getFont();      gfx.setFont(originalFont.deriveFont(java.awt.Font.BOLD));      FontMetrics fm = gfx.getFontMetrics();      int vpad = (box.height - fm.getHeight()) / 2;      gfx.drawString(rep, 2, fm.getHeight() + vpad);      int repwidth = fm.stringWidth(rep);      gfx.setFont(originalFont);      if (m_Object instanceof OptionHandler) {	gfx.drawString(" " + Utils.joinOptions(((OptionHandler)m_Object).getOptions()),					       repwidth + 2, fm.getHeight() + vpad);      }    }  }  /**   * Returns null as we don't support getting/setting values as text.   *   * @return null   */  public String getAsText() {    return null;  }  /**   * Returns null as we don't support getting/setting values as text.    *   * @param text the text value   * @throws IllegalArgumentException as we don't support   * getting/setting values as text.   */  public void setAsText(String text) {    throw new IllegalArgumentException(text);  }  /**   * Returns null as we don't support getting values as tags.   *   * @return null   */  public String[] getTags() {    return null;  }  /**   * Returns true because we do support a custom editor.   *   * @return true   */  public boolean supportsCustomEditor() {    return true;  }    /**   * Returns the array editing component.   *   * @return a value of type 'java.awt.Component'   */  public java.awt.Component getCustomEditor() {    if (m_EditorComponent == null) {      m_EditorComponent = new GOEPanel();    }    return m_EditorComponent;  }  /**   * Adds a PropertyChangeListener who will be notified of value changes.   *   * @param l a value of type 'PropertyChangeListener'   */  public void addPropertyChangeListener(PropertyChangeListener l) {    m_Support.addPropertyChangeListener(l);  }  /**   * Removes a PropertyChangeListener.   *   * @param l a value of type 'PropertyChangeListener'   */  public void removePropertyChangeListener(PropertyChangeListener l) {    m_Support.removePropertyChangeListener(l);  }  /**   * Gets the custom panel used for editing the object.   *   * @return the panel   */  public JPanel getCustomPanel() {    JButton chooseButton = createChooseClassButton();        m_ObjectPropertyPanel = new PropertyPanel(this, true);        JPanel customPanel = new JPanel();    customPanel.setLayout(new BorderLayout());    customPanel.add(chooseButton, BorderLayout.WEST);    customPanel.add(m_ObjectPropertyPanel, BorderLayout.CENTER);    return customPanel;  }  /**   * Creates a button that when clicked will enable the user to change   * the class of the object being edited.   *    * @return the choose button   */  protected JButton createChooseClassButton() {    JButton setButton = new JButton("Choose");    // anonymous action listener shows a JTree popup and allows the user    // to choose the class they want    setButton.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  JPopupMenu popup = getChooseClassPopupMenu();	  // show the popup where the source component is	  if (e.getSource() instanceof Component) {	    Component comp = (Component) e.getSource();	    popup.show(comp, comp.getX(), comp.getY());	    popup.pack();	  }	}      });    return setButton;  }  /**   * creates a classname from the given path   *    * @param path	the path to generate the classname from   * @return		the generated classname   */  protected String getClassnameFromPath(TreePath path) {    StringBuffer classname = new StringBuffer();        // recreate class name from path    int start = 0;    if (m_ObjectNames.size() > 1)      start = 1;    for (int i = start; i < path.getPathCount(); i++) {      if (i>start) classname.append(".");      classname.append(	  (String) ((GOETreeNode) path.getPathComponent(i)).getUserObject());    }        return classname.toString();  }    /**   * Returns a popup menu that allows the user to change   * the class of object.   *   * @return a JPopupMenu that when shown will let the user choose the class   */  public JPopupMenu getChooseClassPopupMenu() {    updateObjectNames();    // create the tree, and find the path to the current class    m_treeNodeOfCurrentObject = null;    final JTree tree = createTree(m_ObjectNames);    if (m_treeNodeOfCurrentObject != null) {      tree.setSelectionPath(new TreePath(m_treeNodeOfCurrentObject.getPath()));    }    tree.getSelectionModel().setSelectionMode      (TreeSelectionModel.SINGLE_TREE_SELECTION);    // create the popup    final JPopupMenu popup = new JTreePopupMenu(tree);    // respond when the user chooses a class    tree.addTreeSelectionListener(new TreeSelectionListener() {	public void valueChanged(TreeSelectionEvent e) {	  GOETreeNode node = (GOETreeNode) tree.getLastSelectedPathComponent();	  	  if (node == null) 	    return;	  	  if (node.isLeaf()) {	    classSelected(getClassnameFromPath(tree.getSelectionPath()));	    popup.setVisible(false);	  }	}      });        return popup;  }  /**   * Creates a JTree from an object heirarchy.   *   * @param hpps the hierarchy of objects to mirror in the tree   * @return a JTree representation of the hierarchy   */  protected JTree createTree(Hashtable hpps) {    GOETreeNode             superRoot;    Enumeration             enm;    HierarchyPropertyParser hpp;        if (hpps.size() > 1)      superRoot = new GOETreeNode("root");    else      superRoot = null;    enm = hpps.elements();    while (enm.hasMoreElements()) {      hpp = (HierarchyPropertyParser) enm.nextElement();      hpp.goToRoot();      GOETreeNode root = new GOETreeNode(hpp.getValue());      addChildrenToTree(root, hpp);            if (superRoot == null)        superRoot = root;      else        superRoot.add(root);    }        JTree tree = new JTree(superRoot);        return tree;  }  /**   * Recursively builds a JTree from an object heirarchy.   * Also updates m_treeNodeOfCurrentObject if the current object   * is discovered during creation.   *   * @param tree the root of the tree to add children to   * @param hpp the hierarchy of objects to mirror in the tree   */  protected void addChildrenToTree(GOETreeNode tree,				   HierarchyPropertyParser hpp) {    try {      for (int i=0; i<hpp.numChildren(); i++) {	hpp.goToChild(i);	GOETreeNode child = new GOETreeNode(hpp.getValue());	if ((m_Object != null) &&	    m_Object.getClass().getName().equals(hpp.fullValue())) {	  m_treeNodeOfCurrentObject = child;	}	tree.add(child);	addChildrenToTree(child, hpp);	hpp.goToParent();      }    } catch (Exception e) {      e.printStackTrace();    }  }  /**   * Called when the user selects an class type to change to.   *   * @param className the name of the class that was selected   */  protected void classSelected(String className) {    try {		          if ((m_Object != null) && m_Object.getClass().getName().equals(className)) {	return;      }            setValue(Class.forName(className).newInstance());      //m_ObjectPropertyPanel.showPropertyDialog();      if (m_EditorComponent != null) {	m_EditorComponent.updateChildPropertySheet();      }    } catch (Exception ex) {      JOptionPane.showMessageDialog(null,				    "Could not create an example of\n"				    + className + "\n"				    + "from the current classpath",				    "Class load failed",				    JOptionPane.ERROR_MESSAGE);      ex.printStackTrace();      try {	if(m_Backup != null)	  setValue(m_Backup);	else	  setDefaultValue();			      } catch(Exception e) {	System.err.println(ex.getMessage());	ex.printStackTrace();      }    }  }    /**   * Sets the capabilities to use for filtering.   *    * @param value	the object to get the filter capabilities from   */  public void setCapabilitiesFilter(Capabilities value) {    m_CapabilitiesFilter = new Capabilities(null);    m_CapabilitiesFilter.assign(value);  }    /**   * Returns the current Capabilities filter, can be null.   *    * @return		the current Capabiliities used for filtering   */  public Capabilities getCapabilitiesFilter() {    return m_CapabilitiesFilter;  }    /**   * Removes the current Capabilities filter.   */  public void removeCapabilitiesFilter() {    m_CapabilitiesFilter = null;  }  /**   * Tests out the Object editor from the command line.   *   * @param args may contain the class name of a Object to edit   */  public static void main(String [] args) {    try {      GenericObjectEditor.registerEditors();      GenericObjectEditor ce = new GenericObjectEditor(true);      ce.setClassType(weka.classifiers.Classifier.class);      Object initial = new weka.classifiers.rules.ZeroR();      if (args.length > 0){	ce.setClassType(Class.forName(args[0]));	if(args.length > 1){	  initial = (Object)Class.forName(args[1]).newInstance();	  ce.setValue(initial);	}	else	  ce.setDefaultValue();      }      else	  	ce.setValue(initial);            PropertyDialog pd = new PropertyDialog(ce, 100, 100);      pd.addWindowListener(new WindowAdapter() {	  public void windowClosing(WindowEvent e) {	    PropertyEditor pe = ((PropertyDialog)e.getSource()).getEditor();	    Object c = (Object)pe.getValue();	    String options = "";	    if (c instanceof OptionHandler) {	      options = Utils.joinOptions(((OptionHandler)c).getOptions());	    }	    System.out.println(c.getClass().getName() + " " + options);	    System.exit(0);	  }	});    } catch (Exception ex) {      ex.printStackTrace();      System.err.println(ex.getMessage());    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?