Adv Java - [Swing: File Dialogs]

♠ Posted by Unknown in at 00:36

File Dialogs


Some operating systems have a number of special built-in dialog boxes to handle the selection of things such as fonts, colors, printer, and the like. Virtually all graphical operating systems support the opening and saving of files, however and so Java’s JFileChooser encapsulates these for easy use.


For an “Open File” dialog, you call showOpenDialog(), and for a “Save File” dialog you call showSaveDialog(). These command don’t return until the dialog is closed. The JFileChooser object still exists, so you can read data from it. The methods getSelectedFile() and getCurrentDirectory() are two ways you interrogate the results of the operation. If these return null it means the user canceled out of the dialog.

Example: 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FileChooserTest extends JApplet implements ActionListener
{
          JTextField filename = new JTextField(), dir = new JTextField();
          JButton open = new JButton("Open"), save = new JButton("Save");
         
          public void init()
          {
                   JPanel p = new JPanel();
                   open.addActionListener(this);
                   p.add(open);
                  
                   save.addActionListener(this);
                   p.add(save);
                  
                   Container contentPane = getContentPane();
                   contentPane.add(p, BorderLayout.SOUTH);
                   dir.setEditable(false);
                   filename.setEditable(false);
                   p = new JPanel();
                   p.setLayout(new GridLayout(2,1));
                   p.add(filename);
                   p.add(dir);
                   contentPane.add(p, BorderLayout.NORTH);
          }
          public void actionPerformed(ActionEvent ae)
          {
                   JFileChooser c = new JFileChooser();
                   int rVal;
                   if(ae.getSource()== open)
                             rVal = c.showOpenDialog(this);
                   else
                   rVal = c.showSaveDialog(this);
                  
                   if(rVal == JFileChooser.APPROVE_OPTION)
                   {
                             filename.setText(c.getSelectedFile().getName());
                             dir.setText(c.getCurrentDirectory().toString());
                   }
                   if(rVal == JFileChooser.CANCEL_OPTION)
                   {
                             filename.setText("You Pressed Cancel...");
                             dir.setText("");
                   }
          }

}

Image: Swing File Dialog Example

0 comments:

Post a Comment