同じく名前を付けて保存ダイアログもFileDialogクラスを使用します。
FileDialogクラスのコンストラクタ
FileDialog(Frame parent)
FileDialog(Frame parent, String title)
FileDialog(Frame parent, String title, int mode)
引数 parent
オーナーとなるフレームを指定します。
引数 title
ダイアログタイトルを指定します。
引数 mode
ファイル開くダイアログの場合は FileDialog.LOAD を指定します。
ファイルを保存ダイアログの場合は FileDialog.SAVE を指定します。
package FileAccess;
import java.awt.*;
import java.awt.event.*;
public class FileDialogSample extends Frame implements ActionListener{
private static final long serialVersionUID = 1L;
public static void main(String args[]){
new FileDialogSample();
}
Label lblPath;
Button btnOpen;
Button btnSave;
public FileDialogSample(){
this.setTitle("FileDialogSample");
this.setSize(300,300);
this.setLayout(new GridLayout(2,1));
lblPath = new Label();
this.add(lblPath);
btnOpen = new Button();
btnOpen.setLabel("ファイルを開くダイアログを表示");
btnOpen.addActionListener(this);
btnSave = new Button();
btnSave.setLabel("名前を付けて保存ダイアログを表示");
btnSave.addActionListener(this);
Panel pnl1 = new Panel();
pnl1.add(btnOpen);
pnl1.add(btnSave);
this.add(pnl1);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnOpen){
FileOpenDialog();
}else if (e.getSource() == btnSave){
FileSaveDialog();
}
}
private void FileOpenDialog(){
String path = null;
FileDialog fd = new FileDialog(this , "ファイルを開く" , FileDialog.LOAD);
try{
fd.setVisible(true);
if (fd.getFile() != null) {
path = fd.getDirectory() + fd.getFile();
}
}finally{
fd.dispose();
}
if (path != null){
lblPath.setText(path);
}else{
lblPath.setText("");
}
}
private void FileSaveDialog(){
String path = null;
FileDialog fd = new FileDialog(this , "名前を付けて保存" , FileDialog.SAVE);
try{
fd.setVisible(true);
if (fd.getFile() != null) {
path = fd.getDirectory() + fd.getFile();
}
}finally{
fd.dispose();
}
if (path != null){
lblPath.setText(path);
}else{
lblPath.setText("");
}
}
}
0 件のコメント:
コメントを投稿