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

📄 genericobjecteditor.java

📁 :<<数据挖掘--实用机器学习技术及java实现>>一书的配套源程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* *    This program is free software; you can redistribute it and/or modify *    it under the terms of the GNU General Public License as published by *    the Free Software Foundation; either version 2 of the License, or *    (at your option) any later version. * *    This program is distributed in the hope that it will be useful, *    but WITHOUT ANY WARRANTY; without even the implied warranty of *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the *    GNU General Public License for more details. * *    You should have received a copy of the GNU General Public License *    along with this program; if not, write to the Free Software *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *//* *    GenericObjectEditor.java *    Copyright (C) 1999 Len Trigg * */package weka.gui;import weka.core.OptionHandler;import weka.core.Utils;import weka.core.Tag;import weka.core.SelectedTag;import weka.core.SerializedObject;import weka.core.Utils;import java.awt.BorderLayout;import java.awt.Component;import java.awt.Dimension;import java.awt.FontMetrics;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.beans.PropertyEditor;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.Properties;import java.util.StringTokenizer;import java.util.Vector;import javax.swing.BorderFactory;import javax.swing.DefaultComboBoxModel;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;/**  * A PropertyEditor for objects that themselves have been defined as * editable in the GenericObjectEditor configuration file, which lists * possible values that can be selected from, and themselves configured. * The configuration file is called "GenericObjectEditor.props" and * may live in either the location given by "user.home" or the current * directory (this last will take precedence), and a default properties * file is read from the weka distribution. For speed, the properties * file is read only once when the class is first loaded -- this may need * to be changed if we ever end up running in a Java OS ;-). * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision: 1.26 $ */public class GenericObjectEditor implements PropertyEditor {  /** The classifier being configured */  private Object m_Object;  /** Holds a copy of the current classifier that can be reverted to      if the user decides to cancel */  private Object m_Backup;    /** Handles property change notification */  private PropertyChangeSupport m_Support = new PropertyChangeSupport(this);  /** The Class of objects being edited */  private Class m_ClassType;  /** The GUI component for editing values, created when needed */  private GOEPanel m_EditorComponent;  /** True if the GUI component is needed */  private boolean m_Enabled = true;    /** The name of the properties file */  protected static String PROPERTY_FILE = "weka/gui/GenericObjectEditor.props";  /** Contains the editor properties */  private static Properties EDITOR_PROPERTIES;  /** Loads the configuration property file */  static {    // Allow a properties file in the current directory to override    try {      EDITOR_PROPERTIES = Utils.readProperties(PROPERTY_FILE);      java.util.Enumeration keys = 	(java.util.Enumeration)EDITOR_PROPERTIES.propertyNames();      if (!keys.hasMoreElements()) {	throw new Exception("Failed to read a property file for the "			    +"generic object editor");      }    } catch (Exception ex) {      JOptionPane.showMessageDialog(null,          "Could not read a configuration file for the generic object\n"         +"editor. An example file is included with the Weka distribution.\n"	 +"This file should be named \"" + PROPERTY_FILE + "\" and\n"	 +"should be placed either in your user home (which is set\n"	 + "to \"" + System.getProperties().getProperty("user.home") + "\")\n"	 + "or the directory that java was started from\n",	 "GenericObjectEditor",	 JOptionPane.ERROR_MESSAGE);    }  }  /**   * Handles the GUI side of editing values.   */  public class GOEPanel extends JPanel implements ItemListener {        /** The chooser component */    private JComboBox m_ObjectChooser;        /** The component that performs classifier customization */    private PropertySheetPanel m_ChildPropertySheet;    /** The model containing the list of names to select from */    private DefaultComboBoxModel m_ObjectNames;    /** Open object from disk */    private JButton m_OpenBut;    /** Save object to disk */    private JButton m_SaveBut;    /** ok button */    private JButton m_okBut;        /** cancel button */    private JButton m_cancelBut;    /** The filechooser for opening and saving object files */    private JFileChooser m_FileChooser;    /** Creates the GUI editor component */    public GOEPanel() {      m_Backup = copyObject(m_Object);      //System.err.println("GOE()");      m_ObjectNames = new DefaultComboBoxModel(new String [0]);      m_ObjectChooser = new JComboBox(m_ObjectNames);      m_ObjectChooser.setEditable(false);      m_ChildPropertySheet = new PropertySheetPanel();      m_ChildPropertySheet.addPropertyChangeListener(      new PropertyChangeListener() {	public void propertyChange(PropertyChangeEvent evt) {	  m_Support.firePropertyChange("", null, null);	}      });      m_OpenBut = new JButton("Open...");      m_OpenBut.setToolTipText("Load a configured object");      m_OpenBut.setEnabled(true);      m_OpenBut.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  Object object = openObject();          if (object != null) {            // setValue takes care of: Making sure obj is of right type,            // and firing property change.            setValue(object);            // Need a second setValue to get property values filled in OK.            // Not sure why.            setValue(object);          }	}      });      m_SaveBut = new JButton("Save...");      m_SaveBut.setToolTipText("Save the current configured object");      m_SaveBut.setEnabled(true);      m_SaveBut.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  saveObject(m_Object);	}      });      m_okBut = new JButton("OK");      m_okBut.setEnabled(true);      m_okBut.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  m_Backup = copyObject(m_Object);	  if ((getTopLevelAncestor() != null)	      && (getTopLevelAncestor() instanceof Window)) {	    Window w = (Window) getTopLevelAncestor();	    w.dispose();	  }	}      });      m_cancelBut = new JButton("Cancel");      m_cancelBut.setEnabled(true);      m_cancelBut.addActionListener(new ActionListener() {	public void actionPerformed(ActionEvent e) {	  if (m_Backup != null) {	    m_Object = copyObject(m_Backup);	    setObject(m_Object);	    updateClassType();	    updateChooser();	    updateChildPropertySheet();	  }	  if ((getTopLevelAncestor() != null)	      && (getTopLevelAncestor() instanceof Window)) {	    Window w = (Window) getTopLevelAncestor();	    w.dispose();	  }	}      });            setLayout(new BorderLayout());      add(m_ObjectChooser, BorderLayout.NORTH);      add(m_ChildPropertySheet, BorderLayout.CENTER);      // Since we resize to the size of the property sheet, a scrollpane isn't      // typically needed      // add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER);      JPanel okcButs = new JPanel();      okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));      okcButs.setLayout(new GridLayout(1, 4, 5, 5));      okcButs.add(m_OpenBut);      okcButs.add(m_SaveBut);      okcButs.add(m_okBut);      okcButs.add(m_cancelBut);      add(okcButs, BorderLayout.SOUTH);            if (m_ClassType != null) {	updateClassType();	updateChooser();	updateChildPropertySheet();      }      m_ObjectChooser.addItemListener(this);    }    /**     * Opens an object from a file selected by the user.     *      * @return the loaded object, or null if the operation was cancelled     */    protected Object openObject() {      if (m_FileChooser == null) {        createFileChooser();      }      int returnVal = m_FileChooser.showOpenDialog(this);      if (returnVal == JFileChooser.APPROVE_OPTION) {	File selected = m_FileChooser.getSelectedFile();	try {	  ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected)));          Object obj = oi.readObject();          oi.close();          if (!m_ClassType.isAssignableFrom(obj.getClass())) {            throw new Exception("Object not of type: " + m_ClassType.getName());          }          return obj;	} catch (Exception ex) {	  JOptionPane.showMessageDialog(this,					"Couldn't read object: "					+ selected.getName() 					+ "\n" + ex.getMessage(),					"Open object file",					JOptionPane.ERROR_MESSAGE);	}      }      return null;    }    /**     * Opens an object from a file selected by the user.     *      * @return the loaded object, or null if the operation was cancelled     */    protected void saveObject(Object object) {      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);	}      }    }    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 {        SerializedObject so = new SerializedObject(source);	result = so.getObject();      } catch (Exception ex) {	System.err.println("GenericObjectEditor: Problem making backup object");	System.err.print(ex);      }      return result;    }    /**      * 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);    }         /** Called when the class of object being edited changes. */    protected void updateClassType() {            Vector classes = getClassesFromProperties();      m_ObjectChooser.setModel(new DefaultComboBoxModel(classes));      if (classes.size() > 0) {	add(m_ObjectChooser, BorderLayout.NORTH);      } else {	remove(m_ObjectChooser);      }    }

⌨️ 快捷键说明

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