Friday, January 10, 2014

How to use SaveAs FileChooser dialog in java

Below shows you how to use SaveAs FileChooser dialog in java. Please remember the main class has to extends a component like JFrame, JPanel or JButton, otherwise will not work.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;

public class SaveButton extends JButton {
private String _filename, _dir;

class SaveL implements ActionListener {
public void actionPerformed(ActionEvent e) {
  JFileChooser c = new JFileChooser();
  // Pop up "Save" dialog:
  int rVal = c.showSaveDialog(SaveButton.this);
  if (rVal == JFileChooser.APPROVE_OPTION) {
    _filename = c.getSelectedFile().getName();
    _dir = c.getCurrentDirectory().toString();
  }
  if (rVal == JFileChooser.CANCEL_OPTION) {
    _filename = null;
    _dir = null;
  }
}
}

public String getFileName(){
return _filename;
}

public String getDirectory(){
return _dir;
}
}

No comments:

Post a Comment