DatasetListPanel.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 12k
Category:

Windows Develop

Development Platform:

Java

  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.  *    DatasetListPanel.java
  18.  *    Copyright (C) 1999 Len Trigg
  19.  *
  20.  */
  21. package weka.gui.experiment;
  22. import weka.core.Instances;
  23. import weka.experiment.Experiment;
  24. import weka.gui.ExtensionFileFilter;
  25. import java.io.File;
  26. import java.util.Vector;
  27. import java.awt.Component;
  28. import java.awt.BorderLayout;
  29. import java.awt.GridLayout;
  30. import java.awt.event.ActionEvent;
  31. import java.awt.event.WindowAdapter;
  32. import java.awt.event.WindowEvent;
  33. import java.awt.event.ActionListener;
  34. import java.awt.GridBagLayout;
  35. import java.awt.GridBagConstraints;
  36. import java.awt.Insets;
  37. import javax.swing.JPanel;
  38. import javax.swing.JLabel;
  39. import javax.swing.JFrame;
  40. import javax.swing.SwingConstants;
  41. import javax.swing.JTextField;
  42. import javax.swing.BorderFactory;
  43. import javax.swing.DefaultListModel;
  44. import javax.swing.JScrollPane;
  45. import javax.swing.JList;
  46. import javax.swing.JButton;
  47. import javax.swing.JFileChooser;
  48. import javax.swing.filechooser.FileFilter;
  49. import javax.swing.JCheckBox;
  50. /** 
  51.  * This panel controls setting a list of datasets for an experiment to
  52.  * iterate over.
  53.  *
  54.  * @author Len Trigg (trigg@cs.waikato.ac.nz)
  55.  * @version $Revision: 1.13 $
  56.  */
  57. public class DatasetListPanel extends JPanel implements ActionListener {
  58.   /** The experiment to set the dataset list of */
  59.   protected Experiment m_Exp;
  60.   /** The component displaying the dataset list */
  61.   protected JList m_List;
  62.   /** Click to add a dataset */
  63.   protected JButton m_AddBut = new JButton("Add new...");
  64.   /** Click to remove the selected dataset from the list */
  65.   protected JButton m_DeleteBut = new JButton("Delete selected");
  66.   /** Make file paths relative to the user (start) directory */
  67.   protected JCheckBox m_relativeCheck = new JCheckBox("Use relative paths");
  68.   /** A filter to ensure only arff files get selected */
  69.   protected FileFilter m_ArffFilter =
  70.     new ExtensionFileFilter(Instances.FILE_EXTENSION, "Arff data files");
  71.   /** The user (start) directory */
  72.   protected File m_UserDir = new File(System.getProperty("user.dir"));
  73.   /** The file chooser component */
  74.   protected JFileChooser m_FileChooser = new JFileChooser(m_UserDir);
  75.   
  76.   /**
  77.    * Creates the dataset list panel with the given experiment.
  78.    *
  79.    * @param exp a value of type 'Experiment'
  80.    */
  81.   public DatasetListPanel(Experiment exp) {
  82.     this();
  83.     setExperiment(exp);
  84.   }
  85.   /**
  86.    * Create the dataset list panel initially disabled.
  87.    */
  88.   public DatasetListPanel() {
  89.     
  90.     m_List = new JList();
  91.     m_FileChooser.setFileFilter(m_ArffFilter);
  92.     // Multiselection isn't handled by the current implementation of the
  93.     // swing look and feels.
  94.     // m_FileChooser.setMultiSelectionEnabled(true);
  95.     m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  96.     m_DeleteBut.setEnabled(false);
  97.     m_DeleteBut.addActionListener(this);
  98.     m_AddBut.setEnabled(false);
  99.     m_AddBut.addActionListener(this);
  100.     m_relativeCheck.setSelected(false);
  101.     m_relativeCheck.setToolTipText("Store file paths relative to "
  102.    +"the start directory");
  103.     setLayout(new BorderLayout());
  104.     setBorder(BorderFactory.createTitledBorder("Datasets"));
  105.     JPanel topLab = new JPanel();
  106.     GridBagLayout gb = new GridBagLayout();
  107.     GridBagConstraints constraints = new GridBagConstraints();
  108.     topLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
  109.     //    topLab.setLayout(new GridLayout(1,2,5,5));
  110.     topLab.setLayout(gb);
  111.    
  112.     constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
  113.     constraints.fill = GridBagConstraints.HORIZONTAL;
  114.     constraints.gridwidth=1;constraints.gridheight=1;
  115.     constraints.insets = new Insets(0,2,0,2);
  116.     topLab.add(m_AddBut,constraints);
  117.     constraints.gridx=1;constraints.gridy=0;constraints.weightx=5;
  118.     constraints.gridwidth=1;constraints.gridheight=1;
  119.     topLab.add(m_DeleteBut,constraints);
  120.     constraints.gridx=0;constraints.gridy=1;constraints.weightx=5;
  121.     constraints.fill = GridBagConstraints.HORIZONTAL;
  122.     constraints.gridwidth=1;constraints.gridheight=1;
  123.     constraints.insets = new Insets(0,2,0,2);
  124.     topLab.add(m_relativeCheck,constraints);
  125.     add(topLab, BorderLayout.NORTH);
  126.     add(new JScrollPane(m_List), BorderLayout.CENTER);
  127.   }
  128.   /**
  129.    * Tells the panel to act on a new experiment.
  130.    *
  131.    * @param exp a value of type 'Experiment'
  132.    */
  133.   public void setExperiment(Experiment exp) {
  134.     m_Exp = exp;
  135.     m_AddBut.setEnabled(true);
  136.     m_List.setModel(m_Exp.getDatasets());
  137.     if (m_Exp.getDatasets().size() > 0) {
  138.       m_DeleteBut.setEnabled(true);
  139.     }
  140.   }
  141.   
  142.   /**
  143.    * Gets all the files in the given directory
  144.    * that match the currently selected extension.
  145.    */
  146.   protected void getFilesRecursively(File directory, Vector files) {
  147.     try {
  148.       String[] currentDirFiles = directory.list();
  149.       for (int i = 0; i < currentDirFiles.length; i++) {
  150. currentDirFiles[i] = directory.getCanonicalPath() + File.separator + 
  151.   currentDirFiles[i];
  152. File current = new File(currentDirFiles[i]);
  153. if (m_FileChooser.getFileFilter().accept(current)) {
  154.   if (current.isDirectory()) {
  155.     getFilesRecursively(current, files);
  156.   } else {
  157.     files.addElement(current);
  158.   }
  159. }
  160.       }
  161.     } catch (Exception e) {
  162.       System.err.println("IOError occured when reading list of files");
  163.     }
  164.   }
  165.   /**
  166.    * Converts a File's absolute path to a path relative to the user
  167.    * (ie start) directory
  168.    * @param absolute the File to convert to relative path
  169.    * @return a File with a path that is relative to the user's directory
  170.    * @exception Exception if the path cannot be constructed
  171.    */
  172.   protected File convertToRelativePath(File absolute) throws Exception {
  173.     String userPath = m_UserDir.getAbsolutePath() + File.separator;
  174.     String targetPath = (new File(absolute.getParent())).getPath() 
  175.       + File.separator;
  176.     String fileName = absolute.getName();
  177.     StringBuffer relativePath = new StringBuffer();
  178.     relativePath.append("."+File.separator);
  179.     //    System.err.println("User dir "+userPath);
  180.     //    System.err.println("Target path "+targetPath);
  181.     
  182.     // file is in user dir (or subdir)
  183.     int subdir = targetPath.indexOf(userPath);
  184.     if (subdir == 0) {
  185.       if (userPath.length() == targetPath.length()) {
  186. relativePath.append(fileName);
  187.       } else {
  188. int ll = userPath.length();
  189. relativePath.append(targetPath.substring(ll));
  190. relativePath.append(fileName);
  191.       }
  192.     } else {
  193.       int sepCount = 0;
  194.       String temp = new String(userPath);
  195.       while (temp.indexOf(File.separator) != -1) {
  196. int ind = temp.indexOf(File.separator);
  197. sepCount++;
  198. temp = temp.substring(ind+1, temp.length());
  199.       }
  200.       
  201.       String targetTemp = new String(targetPath);
  202.       String userTemp = new String(userPath);
  203.       int tcount = 0;
  204.       while (targetTemp.indexOf(File.separator) != -1) {
  205. int ind = targetTemp.indexOf(File.separator);
  206. int ind2 = userTemp.indexOf(File.separator);
  207. String tpart = targetTemp.substring(0,ind+1);
  208. String upart = userTemp.substring(0,ind2+1);
  209. if (tpart.compareTo(upart) != 0) {
  210.   if (tcount == 0) {
  211.     tcount = -1;
  212.   }
  213.   break;
  214. }
  215. tcount++;
  216. targetTemp = targetTemp.substring(ind+1, targetTemp.length());
  217. userTemp = userTemp.substring(ind2+1, userTemp.length());
  218.       }
  219.       if (tcount == -1) {
  220. // then target file is probably on another drive (under windows)
  221. throw new Exception("Can't construct a path to file relative to user "
  222.     +"dir.");
  223.       }
  224.       if (targetTemp.indexOf(File.separator) == -1) {
  225. targetTemp = "";
  226.       }
  227.       for (int i = 0; i < sepCount - tcount; i++) {
  228. relativePath.append(".."+File.separator);
  229.       }
  230.       relativePath.append(targetTemp + fileName);
  231.     }
  232.     //    System.err.println("new path : "+relativePath.toString());
  233.     return new File(relativePath.toString());
  234.   }
  235.   
  236.   /**
  237.    * Handle actions when buttons get pressed.
  238.    *
  239.    * @param e a value of type 'ActionEvent'
  240.    */
  241.   public void actionPerformed(ActionEvent e) {
  242.     boolean useRelativePaths = m_relativeCheck.isSelected();
  243.     if (e.getSource() == m_AddBut) {
  244.       // Let the user select an arff file from a file chooser
  245.       int returnVal = m_FileChooser.showOpenDialog(this);
  246.       if(returnVal == JFileChooser.APPROVE_OPTION) {
  247. if (m_FileChooser.isMultiSelectionEnabled()) {
  248.   File [] selected = m_FileChooser.getSelectedFiles();
  249.   for (int i = 0; i < selected.length; i++) {
  250.     if (selected[i].isDirectory()) {
  251.       Vector files = new Vector();
  252.       getFilesRecursively(selected[i], files);
  253.       for (int j = 0; j < files.size(); j++) {
  254. File temp = (File)files.elementAt(j);
  255. if (useRelativePaths) {
  256.   try {
  257.     temp = convertToRelativePath(temp);
  258.   } catch (Exception ex) {
  259.     ex.printStackTrace();
  260.   }
  261. }
  262. m_Exp.getDatasets().addElement(temp);
  263.       }
  264.     } else {
  265.       File temp = selected[i];
  266.       if (useRelativePaths) {
  267. try {
  268.   temp = convertToRelativePath(temp);
  269. } catch (Exception ex) {
  270.   ex.printStackTrace();
  271. }
  272.       }
  273.       m_Exp.getDatasets().addElement(temp);
  274.     }
  275.   }
  276.   m_DeleteBut.setEnabled(true);
  277. } else {
  278.   if (m_FileChooser.getSelectedFile().isDirectory()) {
  279.     Vector files = new Vector();
  280.     getFilesRecursively(m_FileChooser.getSelectedFile(), files);
  281.     for (int j = 0; j < files.size(); j++) {
  282.       File temp = (File)files.elementAt(j);
  283.       if (useRelativePaths) {
  284. try {
  285.   temp = convertToRelativePath(temp);
  286. } catch (Exception ex) {
  287.   ex.printStackTrace();
  288. }
  289.       }
  290.       m_Exp.getDatasets().addElement(temp);
  291.     }
  292.   } else {
  293.     File temp = m_FileChooser.getSelectedFile();
  294.     if (useRelativePaths) {
  295.       try {
  296. temp = convertToRelativePath(temp);
  297.       } catch (Exception ex) {
  298. ex.printStackTrace();
  299.       }
  300.     }
  301.     m_Exp.getDatasets().addElement(temp);
  302.   }
  303.   m_DeleteBut.setEnabled(true);
  304. }
  305.       }
  306.     } else if (e.getSource() == m_DeleteBut) {
  307.       // Delete the selected files
  308.       int [] selected = m_List.getSelectedIndices();
  309.       if (selected != null) {
  310. for (int i = selected.length - 1; i >= 0; i--) {
  311.   int current = selected[i];
  312.   m_Exp.getDatasets().removeElementAt(current);
  313.   if (m_Exp.getDatasets().size() > current) {
  314.     m_List.setSelectedIndex(current);
  315.   } else {
  316.     m_List.setSelectedIndex(current - 1);
  317.   }
  318. }
  319.       }
  320.       if (m_List.getSelectedIndex() == -1) {
  321. m_DeleteBut.setEnabled(false);
  322.       }
  323.     }
  324.   }
  325.   /**
  326.    * Tests out the dataset list panel from the command line.
  327.    *
  328.    * @param args ignored
  329.    */
  330.   public static void main(String [] args) {
  331.     try {
  332.       final JFrame jf = new JFrame("Dataset List Editor");
  333.       jf.getContentPane().setLayout(new BorderLayout());
  334.       DatasetListPanel dp = new DatasetListPanel();
  335.       jf.getContentPane().add(dp,
  336.       BorderLayout.CENTER);
  337.       jf.addWindowListener(new WindowAdapter() {
  338. public void windowClosing(WindowEvent e) {
  339.   jf.dispose();
  340.   System.exit(0);
  341. }
  342.       });
  343.       jf.pack();
  344.       jf.setVisible(true);
  345.       System.err.println("Short nap");
  346.       Thread.currentThread().sleep(3000);
  347.       System.err.println("Done");
  348.       dp.setExperiment(new Experiment());
  349.     } catch (Exception ex) {
  350.       ex.printStackTrace();
  351.       System.err.println(ex.getMessage());
  352.     }
  353.   }
  354. }