Using Open and Save File Choosers in Applets

Your files are protected from damage by applets; this demonstration will not work with an unsigned jar file. You can sign your own jar files as detailed clearly here. The end user can inspect the details input by the programmer during the signing process and see who the signer claims to be. However, for authentication of a final product you need a trustworthy certificate from an authority such as VeriSign.

These three screenshots show the test text, the save dialog and the open dialog that recovered the same text.

Test Text

Test Text

Save Dialog

Save Dialog

Open Dialog

Open Dialog

Writing your code should not be too difficult when you have an example like this to work from. The methods showSaveDialog and showOpenDialog return the integer JFileChooser.APPROVE_OPTION when you press the "Save" button and "Open" button, respectively. The RandomAccessFile constructor requires for its first parameter the full pathname of the file about to be saved or opened.

namespace file_dialog_demo;
//http://wiki.plexinfo.net/index.php?title=How_to_sign_JAR_files

interface

uses
  java.util, java.applet.*, java.awt.*, javax.swing, java.io;
type
  FileDialogDemo = public class(Applet, ActionListener)
  private
    btnLoad, btnSave : Button;
    ta : JTextArea;
    raf : RandomAccessFile;
  public
    method init; override;
    method actionPerformed(e : ActionEvent);   
  end;

implementation

method FileDialogDemo.init;
begin
  Background := Color.green.darker;
  btnLoad := new Button('Load from File');
  add(btnLoad);
  btnLoad.addActionListener(self);
  btnSave := new Button('Save to File');
  add(btnSave);
  btnSave.addActionListener(self);
  ta := new JTextArea(20, 20);
  ta.setLineWrap(true);
  ta.setWrapStyleWord(true);
  add(ta);
end;

method FileDialogDemo.actionPerformed(e : ActionEvent);
var
  filename, currentLine : String; 
  fc : JFileChooser;
  returnVal : Integer;
  totalContent : String;
  
begin
  if e.getSource = btnLoad then
    begin 
      fc := new JFileChooser;
      returnVal := fc.showOpenDialog(self);
      if returnVal = JFileChooser.APPROVE_OPTION then
        begin     
          filename := fc.getSelectedFile.getAbsolutePath;
          raf := new RandomAccessFile(filename, 'r');
          totalContent := raf.readUTF;
          ta.setText(totalContent);
          raf.close;
        end;      
    end;

  if e.getSource = btnSave then
    begin 
      fc := new JFileChooser;
      returnVal := fc.showSaveDialog(self);
      if returnVal = JFileChooser.APPROVE_OPTION then
        begin     
          filename := fc.getSelectedFile.getAbsolutePath;
          raf := new RandomAccessFile(filename, 'rw');
          totalContent := ta.getText;
          raf.writeUTF(totalContent); 
          raf.close;
        end;      
    end;
end;

end.


Programming - a skill for life!

How to use Dialogues in applets in Oxygene for Java