source: src/main/java/weka/gui/experiment/DatasetListPanel.java @ 4

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

Import di weka.

File size: 13.7 KB
Line 
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 *    DatasetListPanel.java
19 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
20 *
21 */
22
23package weka.gui.experiment;
24
25import weka.core.ClassDiscovery.StringCompare;
26import weka.core.converters.ConverterUtils;
27import weka.core.converters.Saver;
28import weka.core.converters.ConverterUtils.DataSource;
29import weka.core.Utils;
30import weka.experiment.Experiment;
31import weka.gui.ConverterFileChooser;
32import weka.gui.JListHelper;
33import weka.gui.ViewerDialog;
34
35import java.awt.BorderLayout;
36import java.awt.GridBagConstraints;
37import java.awt.GridBagLayout;
38import java.awt.Insets;
39import java.awt.event.ActionEvent;
40import java.awt.event.ActionListener;
41import java.awt.event.MouseAdapter;
42import java.awt.event.MouseEvent;
43import java.awt.event.MouseListener;
44import java.awt.event.WindowAdapter;
45import java.awt.event.WindowEvent;
46import java.io.File;
47import java.util.Collections;
48import java.util.Vector;
49
50import javax.swing.BorderFactory;
51import javax.swing.JButton;
52import javax.swing.JCheckBox;
53import javax.swing.JFileChooser;
54import javax.swing.JFrame;
55import javax.swing.JList;
56import javax.swing.JOptionPane;
57import javax.swing.JPanel;
58import javax.swing.JScrollPane;
59import javax.swing.event.ListSelectionEvent;
60import javax.swing.event.ListSelectionListener;
61
62/**
63 * This panel controls setting a list of datasets for an experiment to
64 * iterate over.
65 *
66 * @author Len Trigg (trigg@cs.waikato.ac.nz)
67 * @version $Revision: 1.27 $
68 */
69public class DatasetListPanel
70  extends JPanel
71  implements ActionListener {
72
73  /** for serialization. */
74  private static final long serialVersionUID = 7068857852794405769L;
75
76  /** The experiment to set the dataset list of. */
77  protected Experiment m_Exp;
78
79  /** The component displaying the dataset list. */
80  protected JList m_List;
81
82  /** Click to add a dataset. */
83  protected JButton m_AddBut = new JButton("Add new...");
84 
85  /** Click to edit the selected algorithm. */
86  protected JButton m_EditBut = new JButton("Edit selected...");
87
88  /** Click to remove the selected dataset from the list. */
89  protected JButton m_DeleteBut = new JButton("Delete selected");
90 
91  /** Click to move the selected dataset(s) one up. */
92  protected JButton m_UpBut = new JButton("Up");
93 
94  /** Click to move the selected dataset(s) one down. */
95  protected JButton m_DownBut = new JButton("Down");
96
97  /** Make file paths relative to the user (start) directory. */
98  protected JCheckBox m_relativeCheck = new JCheckBox("Use relative paths");
99
100  /** The user (start) directory. */
101  //  protected File m_UserDir = new File(System.getProperty("user.dir"));
102
103  /** The file chooser component. */
104  protected ConverterFileChooser m_FileChooser = 
105    new ConverterFileChooser(ExperimenterDefaults.getInitialDatasetsDirectory());
106
107 
108  /**
109   * Creates the dataset list panel with the given experiment.
110   *
111   * @param exp a value of type 'Experiment'
112   */
113  public DatasetListPanel(Experiment exp) {
114
115    this();
116    setExperiment(exp);
117  }
118
119  /**
120   * Create the dataset list panel initially disabled.
121   */
122  public DatasetListPanel() {
123   
124    m_List = new JList();
125    m_List.addListSelectionListener(new ListSelectionListener() {
126        public void valueChanged(ListSelectionEvent e) {
127          setButtons(e);
128        }
129      });
130    MouseListener mouseListener = new MouseAdapter() {
131      public void mouseClicked(MouseEvent e) {
132        if (e.getClickCount() == 2) {
133          // unfortunately, locationToIndex only returns the nearest entry
134          // and not the exact one, i.e. if there's one item in the list and
135          // one doublelclicks somewhere in the list, this index will be
136          // returned
137          int index = m_List.locationToIndex(e.getPoint());
138          if (index > -1)
139            actionPerformed(new ActionEvent(m_EditBut, 0, ""));
140        }
141      }
142    };
143    m_List.addMouseListener(mouseListener);
144   
145    //m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
146    m_FileChooser.setCoreConvertersOnly(true);
147    m_FileChooser.setMultiSelectionEnabled(true);
148    m_FileChooser.setFileSelectionMode(ConverterFileChooser.FILES_AND_DIRECTORIES);
149    m_FileChooser.setAcceptAllFileFilterUsed(false);
150    m_DeleteBut.setEnabled(false);
151    m_DeleteBut.addActionListener(this);
152    m_AddBut.setEnabled(false);
153    m_AddBut.addActionListener(this);
154    m_EditBut.setEnabled(false);
155    m_EditBut.addActionListener(this);
156    m_UpBut.setEnabled(false);
157    m_UpBut.addActionListener(this);
158    m_DownBut.setEnabled(false);
159    m_DownBut.addActionListener(this);
160    m_relativeCheck.setSelected(ExperimenterDefaults.getUseRelativePaths());
161    m_relativeCheck.setToolTipText("Store file paths relative to "
162                                   +"the start directory");
163    setLayout(new BorderLayout());
164    setBorder(BorderFactory.createTitledBorder("Datasets"));
165    JPanel topLab = new JPanel();
166    GridBagLayout gb = new GridBagLayout();
167    GridBagConstraints constraints = new GridBagConstraints();
168    topLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
169    //    topLab.setLayout(new GridLayout(1,2,5,5));
170    topLab.setLayout(gb);
171   
172    constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
173    constraints.fill = GridBagConstraints.HORIZONTAL;
174    constraints.gridwidth=1;constraints.gridheight=1;
175    constraints.insets = new Insets(0,2,0,2);
176    topLab.add(m_AddBut,constraints);
177    constraints.gridx=1;constraints.gridy=0;constraints.weightx=5;
178    constraints.gridwidth=1;constraints.gridheight=1;
179    topLab.add(m_EditBut,constraints);
180    constraints.gridx=2;constraints.gridy=0;constraints.weightx=5;
181    constraints.gridwidth=1;constraints.gridheight=1;
182    topLab.add(m_DeleteBut,constraints);
183
184    constraints.gridx=0;constraints.gridy=1;constraints.weightx=5;
185    constraints.fill = GridBagConstraints.HORIZONTAL;
186    constraints.gridwidth=1;constraints.gridheight=1;
187    constraints.insets = new Insets(0,2,0,2);
188    topLab.add(m_relativeCheck,constraints);
189
190    JPanel bottomLab = new JPanel();
191    gb = new GridBagLayout();
192    constraints = new GridBagConstraints();
193    bottomLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
194    bottomLab.setLayout(gb);
195   
196    constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
197    constraints.fill = GridBagConstraints.HORIZONTAL;
198    constraints.gridwidth=1;constraints.gridheight=1;
199    constraints.insets = new Insets(0,2,0,2);
200    bottomLab.add(m_UpBut,constraints);
201    constraints.gridx=1;constraints.gridy=0;constraints.weightx=5;
202    constraints.gridwidth=1;constraints.gridheight=1;
203    bottomLab.add(m_DownBut,constraints);
204
205    add(topLab, BorderLayout.NORTH);
206    add(new JScrollPane(m_List), BorderLayout.CENTER);
207    add(bottomLab, BorderLayout.SOUTH);
208  }
209 
210  /**
211   * sets the state of the buttons according to the selection state of the
212   * JList.
213   *
214   * @param e the event
215   */
216  private void setButtons(ListSelectionEvent e) {
217    if ( (e == null) || (e.getSource() == m_List) ) {
218      m_DeleteBut.setEnabled(m_List.getSelectedIndex() > -1);
219      m_EditBut.setEnabled(m_List.getSelectedIndices().length == 1);
220      m_UpBut.setEnabled(JListHelper.canMoveUp(m_List));
221      m_DownBut.setEnabled(JListHelper.canMoveDown(m_List));
222    }
223  }
224
225  /**
226   * Tells the panel to act on a new experiment.
227   *
228   * @param exp a value of type 'Experiment'
229   */
230  public void setExperiment(Experiment exp) {
231
232    m_Exp = exp;
233    m_List.setModel(m_Exp.getDatasets());
234    m_AddBut.setEnabled(true);
235    setButtons(null);
236  }
237 
238  /**
239   * Gets all the files in the given directory
240   * that match the currently selected extension.
241   *
242   * @param directory the directory to get the files for
243   * @param files the list to add the files to
244   */
245  protected void getFilesRecursively(File directory, Vector files) {
246
247    try {
248      String[] currentDirFiles = directory.list();
249      for (int i = 0; i < currentDirFiles.length; i++) {
250        currentDirFiles[i] = directory.getCanonicalPath() + File.separator + 
251          currentDirFiles[i];
252        File current = new File(currentDirFiles[i]);
253        if (m_FileChooser.getFileFilter().accept(current)) {
254          if (current.isDirectory()) {
255            getFilesRecursively(current, files);
256          } else {
257            files.addElement(current);
258          }
259        }
260      }
261    } catch (Exception e) {
262      System.err.println("IOError occured when reading list of files");
263    }
264  }
265 
266  /**
267   * Handle actions when buttons get pressed.
268   *
269   * @param e a value of type 'ActionEvent'
270   */
271  public void actionPerformed(ActionEvent e) {
272    boolean useRelativePaths = m_relativeCheck.isSelected();
273
274    if (e.getSource() == m_AddBut) {
275      // Let the user select an arff file from a file chooser
276      int returnVal = m_FileChooser.showOpenDialog(this);
277      if(returnVal == JFileChooser.APPROVE_OPTION) {
278        if (m_FileChooser.isMultiSelectionEnabled()) {
279          File [] selected = m_FileChooser.getSelectedFiles();
280          for (int i = 0; i < selected.length; i++) {
281            if (selected[i].isDirectory()) {
282              Vector files = new Vector();
283              getFilesRecursively(selected[i], files);
284   
285              // sort the result
286              Collections.sort(files, new StringCompare());
287
288              for (int j = 0; j < files.size(); j++) {
289                File temp = (File)files.elementAt(j);
290                if (useRelativePaths) {
291                  try {
292                    temp = Utils.convertToRelativePath(temp);
293                  } catch (Exception ex) {
294                    ex.printStackTrace();
295                  }
296                }
297                m_Exp.getDatasets().addElement(temp);
298              }
299            } else {
300              File temp = selected[i];
301              if (useRelativePaths) {
302                try {
303                  temp = Utils.convertToRelativePath(temp);
304                } catch (Exception ex) {
305                  ex.printStackTrace();
306                }
307              }
308              m_Exp.getDatasets().addElement(temp);
309            }
310          }
311          setButtons(null);
312        } else {
313          if (m_FileChooser.getSelectedFile().isDirectory()) {
314            Vector files = new Vector();
315            getFilesRecursively(m_FileChooser.getSelectedFile(), files);
316   
317            // sort the result
318            Collections.sort(files, new StringCompare());
319
320            for (int j = 0; j < files.size(); j++) {
321              File temp = (File)files.elementAt(j);
322              if (useRelativePaths) {
323                try {
324                  temp = Utils.convertToRelativePath(temp);
325                } catch (Exception ex) {
326                  ex.printStackTrace();
327                }
328              }
329              m_Exp.getDatasets().addElement(temp);
330            }
331          } else {
332            File temp = m_FileChooser.getSelectedFile();
333            if (useRelativePaths) {
334              try {
335                temp = Utils.convertToRelativePath(temp);
336              } catch (Exception ex) {
337                ex.printStackTrace();
338              }
339            }
340            m_Exp.getDatasets().addElement(temp);
341          }
342          setButtons(null);
343        }
344      }
345    } else if (e.getSource() == m_DeleteBut) {
346      // Delete the selected files
347      int [] selected = m_List.getSelectedIndices();
348      if (selected != null) {
349        for (int i = selected.length - 1; i >= 0; i--) {
350          int current = selected[i];
351          m_Exp.getDatasets().removeElementAt(current);
352          if (m_Exp.getDatasets().size() > current) {
353            m_List.setSelectedIndex(current);
354          } else {
355            m_List.setSelectedIndex(current - 1);
356          }
357        }
358      }
359      setButtons(null);
360    } else if (e.getSource() == m_EditBut) {
361      // Delete the selected files
362      int selected = m_List.getSelectedIndex();
363      if (selected != -1) {
364        ViewerDialog dialog = new ViewerDialog(null);
365        String filename = m_List.getSelectedValue().toString();
366        int result;
367        try {
368          DataSource source = new DataSource(filename);
369          result = dialog.showDialog(source.getDataSet());
370          // nasty workaround for Windows regarding locked files:
371          // if file Reader in Loader is not closed explicitly, we cannot
372          // overwrite the file.
373          source = null;
374          System.gc();
375          // workaround end
376          if ((result == ViewerDialog.APPROVE_OPTION) && (dialog.isChanged())) {
377            result = JOptionPane.showConfirmDialog(
378                        this,
379                        "File was modified - save changes?");
380            if (result == JOptionPane.YES_OPTION) {
381              Saver saver = ConverterUtils.getSaverForFile(filename);
382              saver.setFile(new File(filename));
383              saver.setInstances(dialog.getInstances());
384              saver.writeBatch();
385            }
386          }
387        }
388        catch (Exception ex) {
389          JOptionPane.showMessageDialog(
390              this,
391              "Error loading file '" + filename + "':\n" + ex.toString(),
392              "Error loading file",
393              JOptionPane.INFORMATION_MESSAGE);
394        }
395      }
396      setButtons(null);
397    } else if (e.getSource() == m_UpBut) {
398      JListHelper.moveUp(m_List);
399    } else if (e.getSource() == m_DownBut) {
400      JListHelper.moveDown(m_List);
401    }
402  }
403
404  /**
405   * Tests out the dataset list panel from the command line.
406   *
407   * @param args ignored
408   */
409  public static void main(String [] args) {
410
411    try {
412      final JFrame jf = new JFrame("Dataset List Editor");
413      jf.getContentPane().setLayout(new BorderLayout());
414      DatasetListPanel dp = new DatasetListPanel();
415      jf.getContentPane().add(dp,
416                              BorderLayout.CENTER);
417      jf.addWindowListener(new WindowAdapter() {
418        public void windowClosing(WindowEvent e) {
419          jf.dispose();
420          System.exit(0);
421        }
422      });
423      jf.pack();
424      jf.setVisible(true);
425      System.err.println("Short nap");
426      Thread.currentThread().sleep(3000);
427      System.err.println("Done");
428      dp.setExperiment(new Experiment());
429    } catch (Exception ex) {
430      ex.printStackTrace();
431      System.err.println(ex.getMessage());
432    }
433  }
434}
Note: See TracBrowser for help on using the repository browser.