⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 genericobjecteditor.java

📁 MacroWeka扩展了著名数据挖掘工具weka
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
      if (m_FileChooser == null) {
	createFileChooser();
      }
      int returnVal = m_FileChooser.showSaveDialog(this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
	File sFile = m_FileChooser.getSelectedFile();
	try {
	  ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile)));
	  oo.writeObject(object);
	  oo.close();
	} catch (Exception ex) {
	  JOptionPane.showMessageDialog(this,
					"Couldn't write to file: "
					+ sFile.getName() 
					+ "\n" + ex.getMessage(),
					"Save object",
					JOptionPane.ERROR_MESSAGE);
	}
      }
    }

    /**
     * Creates the file chooser the user will use to save/load files with.
     */
    protected void createFileChooser() {
      
      m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir")));
      m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    }

    /**
     * Makes a copy of an object using serialization
     * @param source the object to copy
     * @return a copy of the source object
     */
    protected Object copyObject(Object source) {

      Object result = null;
      try {
        result = GenericObjectEditor.this.makeCopy(source);
	setCancelButton(true);
	
      } catch (Exception ex) {
	setCancelButton(false);
	System.err.println("GenericObjectEditor: Problem making backup object");
	System.err.println(ex);
      }
      return result;
    }
        
    /**
     * Allows customization of the action label on the dialog.
     * @param newLabel the new string for the ok button
     */
    public void setOkButtonText(String newLabel) {

      m_okBut.setText(newLabel);
    }

    /** 
     * This is used to hook an action listener to the ok button
     * @param a The action listener.
     */
    public void addOkListener(ActionListener a) {

      m_okBut.addActionListener(a);
    }
    
    /**
     * This is used to hook an action listener to the cancel button
     * @param a The action listener.
     */
    public void addCancelListener(ActionListener a) {

      m_cancelBut.addActionListener(a);
    }
	
    /**
     * This is used to remove an action listener from the ok button
     * @param a The action listener
     */
    public void removeOkListener(ActionListener a) {

      m_okBut.removeActionListener(a);
    }
    
    /**
     * This is used to remove an action listener from the cancel button
     * @param a The action listener
     */
    public void removeCancelListener(ActionListener a) {

      m_cancelBut.removeActionListener(a);
    }
    
    /** Updates the child property sheet, and creates if needed */
    public void updateChildPropertySheet() {
      
      // Update the object name displayed
      String className = "None";
      if (m_Object != null) {
	className = m_Object.getClass().getName();
      }
      m_ClassNameLabel.setText(className);

      // Set the object as the target of the propertysheet
      m_ChildPropertySheet.setTarget(m_Object);

      // Adjust size of containing window if possible
      if ((getTopLevelAncestor() != null)
	  && (getTopLevelAncestor() instanceof Window)) {
	((Window) getTopLevelAncestor()).pack();
      }
    }	
  }

  /**
   * Default constructor.
   */
  public GenericObjectEditor() {

    this(false);
  }

  /**
   * Constructor that allows specifying whether it is possible
   * to change the class within the editor dialog.
   *
   * @param canChangeClassInDialog whether the user can change the class
   */
  public GenericObjectEditor(boolean canChangeClassInDialog) {

    m_canChangeClassInDialog = canChangeClassInDialog;
  }
  
  /**
   * registers all the editors in Weka
   */
  public static void registerEditors() {
    if (m_EditorsRegistered)
      return;
    
    System.err.println("---Registering Weka Editors---");
    m_EditorsRegistered = true;

    // general
    java.beans.PropertyEditorManager.registerEditor(
        Object[].class,
        weka.gui.GenericArrayEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        java.io.File.class,
        FileEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        java.text.SimpleDateFormat.class,
        SimpleDateFormatEditor.class);
    
    // core
    java.beans.PropertyEditorManager.registerEditor(
        weka.core.SelectedTag.class, 
        weka.gui.SelectedTagEditor.class);
    
    // converters
    java.beans.PropertyEditorManager.registerEditor(
        weka.core.converters.Loader.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.core.converters.Saver.class,
        weka.gui.GenericObjectEditor.class);
    
    // estimators
    java.beans.PropertyEditorManager.registerEditor(
	weka.estimators.Estimator.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.estimators.Estimator[].class, 
        weka.gui.GenericArrayEditor.class);
    
    // filters
    java.beans.PropertyEditorManager.registerEditor(
        weka.filters.Filter.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.filters.Filter[].class, 
        weka.gui.GenericArrayEditor.class);
    
    // classifiers
    java.beans.PropertyEditorManager.registerEditor(
        weka.classifiers.Classifier.class, 
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.classifiers.Classifier[].class, 
        weka.gui.GenericArrayEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.classifiers.CostMatrix.class, 
        weka.gui.CostMatrixEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.classifiers.bayes.net.search.SearchAlgorithm.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.classifiers.bayes.net.estimate.BayesNetEstimator.class,
        weka.gui.GenericObjectEditor.class);
    
    // experiment
    java.beans.PropertyEditorManager.registerEditor(
        weka.experiment.ResultListener.class,
        GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.experiment.ResultProducer.class,
        GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.experiment.SplitEvaluator.class,
        GenericObjectEditor.class);
    

    // associations
    java.beans.PropertyEditorManager.registerEditor(
        weka.associations.Associator.class,
        weka.gui.GenericObjectEditor.class);
    
    // clusterers
    java.beans.PropertyEditorManager.registerEditor(
        weka.clusterers.Clusterer.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.clusterers.DensityBasedClusterer.class,
        weka.gui.GenericObjectEditor.class);
    
    // attribute selection
    java.beans.PropertyEditorManager.registerEditor(
        weka.attributeSelection.ASEvaluation.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.attributeSelection.ASSearch.class,
        weka.gui.GenericObjectEditor.class);
    java.beans.PropertyEditorManager.registerEditor(
        weka.attributeSelection.UnsupervisedSubsetEvaluator.class,
         GenericObjectEditor.class);
  }

  
  /**
   * returns the name of the root element of the given class name, 
   * <code>null</code> if it doesn't contain the separator
   */
  protected static String getRootFromClass(String clsname, String separator) {
    if (clsname.indexOf(separator) > -1)
      return clsname.substring(0, clsname.indexOf(separator));
    else
      return null;
  }

  /**
   * Returns the backup object (may be null if there is no
   * backup).
   *
   * @return the backup object
   */
  public Object getBackup() {
    return m_Backup;
  }

  /**
   * parses the given string of classes separated by ", " and returns the
   * a hashtable with as many entries as there are different root elements in 
   * the class names (the key is the root element). E.g. if there's only 
   * "weka." as the prefix for all classes the a hashtable of size 1 is returned. 
   * if NULL is the input, then NULL is also returned.
   * 
   * @param classes the classnames to work on
   * @return for each distinct root element in the classnames, one entry in
   * the hashtable (with the root element as key)
   */
  public static Hashtable sortClassesByRoot(String classes) {
    Hashtable                 roots;
    Hashtable                 result;
    Enumeration               enm;
    int                       i;
    StringTokenizer           tok;
    String                    clsname;
    Vector                    list;
    HierarchyPropertyParser   hpp;
    String                    separator;
    String                    root;
    String                    tmpStr;
    
    if (classes == null)
      return null;
    
    roots     = new Hashtable();
    hpp       = new HierarchyPropertyParser();
    separator = hpp.getSeperator();
    
    // go over all classnames and store them in the hashtable, with the
    // root element as the key
    tok   = new StringTokenizer(classes, ", ");
    while (tok.hasMoreElements()) {
      clsname = tok.nextToken();
      root    = getRootFromClass(clsname, separator);
      if (root == null)
        continue;
      
      // already stored?
      if (!roots.containsKey(root)) {
        list = new Vector();
        roots.put(root, list);
      }
      else {
        list = (Vector) roots.get(root);
      }
      
      list.add(clsname);
    }
    
    // build result
    result = new Hashtable();
    enm    = roots.keys();
    while (enm.hasMoreElements()) {
      root = (String) enm.nextElement();
      list = (Vector) roots.get(root);
      tmpStr = "";
      for (i = 0; i < list.size(); i++) {
        if (i > 0)
          tmpStr += ",";
        tmpStr += (String) list.get(i);
      }
      result.put(root, tmpStr);
    }
      
    return result;
  }

  /** Called when the class of object being edited changes. */
  protected Hashtable getClassesFromProperties() {	    

    Hashtable hpps = new Hashtable();
    String className = m_ClassType.getName();
    Hashtable typeOptions = sortClassesByRoot(EDITOR_PROPERTIES.getProperty(className));
    if (typeOptions == null) {
      /*
      System.err.println("Warning: No configuration property found in\n"
			 + PROPERTY_FILE + "\n"
			 + "for " + className);
      */
    } else {		    
      try {
        Enumeration enm = typeOptions.keys();
        while (enm.hasMoreElements()) {
          String root = (String) enm.nextElement();
          String typeOption = (String) typeOptions.get(root);
          HierarchyPropertyParser hpp = new HierarchyPropertyParser();
          hpp.build(typeOption, ", ");
	  hpps.put(root, hpp);
        }
      } catch (Exception ex) {
	System.err.println("Invalid property: " + typeOptions);
      }	    
    }
    return hpps;
  }
  
  /**
   * Updates the list of selectable object names, adding any new names to the list.
   */
  protected void updateObjectNames() {
    
    if (m_ObjectNames == null) {
      m_ObjectNames = getClassesFromProperties();
    }
    
    if (m_Object != null) {
      String className = m_Object.getClass().getName();
      String root = getRootFromClass(className, new HierarchyPropertyParser().getSeperator());
      HierarchyPropertyParser hpp = (HierarchyPropertyParser) m_ObjectNames.get(root);
      if (hpp != null) {
        if(!hpp.contains(className)){
          hpp.add(className);
        }
      }
    }
  }
  
  /**
   * Sets whether the editor is "enabled", meaning that the current
   * values will be painted.
   *
   * @param newVal a value of type 'boolean'
   */
  public void setEnabled(boolean newVal) {
    
    if (newVal != m_Enabled) {
      m_Enabled = newVal;
    }
  }
  
  /**
   * Sets the class of values that can be edited.
   *
   * @param type a value of type 'Class'
   */
  public void setClassType(Class type) {
    
    m_ClassType = type;
    m_ObjectNames = getClassesFromProperties();
  }
  
  /**
   * Sets the current object to be the default, taken as the first item in
   * the chooser
   */
  public void setDefaultValue() {
    
    if (m_ClassType == null) {
      System.err.println("No ClassType set up for GenericObjectEditor!!");
      return;
    }	
    
    Hashtable hpps = getClassesFromProperties();
    HierarchyPropertyParser hpp = null;
    Enumeration enm = hpps.elements();
    
    try{
      while (enm.hasMoreElements()) {
        hpp = (HierarchyPropertyParser) enm.nextElement(); 
        if(hpp.depth() > 0) {		
          hpp.goToRoot();
          while(!hpp.isLeafReached())
            hpp.goToChild(0);
          
          String defaultValue = hpp.fullValue();
          setValue(Class.forName(defaultValue).newInstance());
        }
      }
    }catch(Exception ex){
      System.err.println("Problem loading the first class: "+
			 hpp.fullValue());
      ex.printStackTrace();
    }
  }
  
  /**
   * Sets the current Object. If the Object is in the
   * Object chooser, this becomes the selected item (and added
   * to the chooser if necessary).
   *
   * @param o an object that must be a Object.
   */
  public void setValue(Object o) {
    
    if (m_ClassType == null) {
      System.err.println("No ClassType set up for GenericObjectEditor!!");
      return;
    }

⌨️ 快捷键说明

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