金曜日, 1月 16, 2009

JFileChooser: Directory Selection



Java's JFileChooser is a handy UI component in file(s) or directory(directories) selection. As with all Java OOP classes, the set up of the JFileChooser class goes through four steps: 1. instantiate the class 2. set the parameters 3. show off the class 4. wait for the return value (is modal). The JFileChooser class works fine with file selections -- selecting a single/multiple files, setting file extension filters, and retrieve a new file name if the file does not exist.

The trouble is, the case with a directory/directories selection. The JFileChooser class can filter out all the file names, and that part is ok. But when the user enters a new directory name, the filtering would hinder the class to get the non-existent directory name. The user can not select non-existent directory name.

Here shows DirFilter class that can avoid the situation and let the application have the choice either to create or reject the user request.



class DirFilter extends javax.swing.filechooser.FileFilter
{
public String getDescription()
{
return "Directories";
}
public boolean accept(File file)
{
if(file.exists())
{
if(file.isDirectory())
{
return true;
}
else
{
return false;
}
}
else
{
file.mkdir();
return true;
}
}
}



The idea is, to set up a filter for the JFileChooser class, by passing the filter class to JFileChooser. Then the application can decide whether to create a directory of the specified name or to discard it. The filter class should be the one that FileFilter interface be implemented. A word of caution is that there are java.io.FileFilter and javax.swing.filechooser.FileFilter -- the latter should be specified.

The following shows the setting of the new filter class via addChoosableFileFilter() method.



JFileChooser dlg=new JFileChooser(".");
dlg.setDialogType(JFileChooser.SAVE_DIALOG);
dlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
dlg.addChoosableFileFilter(new DirFilter());
int retval=dlg.showDialog(this,null);
if(retval==JFileChooser.APPROVE_OPTION)
{
...

Qt: 外部プログラムを起動する

  Qt/C++ のアプリは、外部へ直接アクセスできます。これはネットアプリでは不可能な Qt のメリットです。 外部プログラムを起動することもできます。QProcess::startDetached() を使うと独立したプロセスを立ち上げることができます。 この QProces...