2007年11月8日木曜日

テキストの保存

ファイル選択ダイアログを表示し、ユーザにファイルを選択させる。
Windowsマシン向けに改行コードを\r\nへ変換している点に注意。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class FileDialogTest extends JFrame implements ActionListener {
private JTextArea textarea = new JTextArea();
private JButton button = new JButton("名前を付けて保存(S)");
public static void main(String[] args) {
FileDialogTest frame = new FileDialogTest();
frame.setTitle("text editor sample");
frame.setSize(480, 320);
frame.setVisible(true);
}

public FileDialogTest() {
button.setMnemonic(KeyEvent.VK_S);
button.addActionListener(this);
this.setLayout(new BorderLayout());
this.add(button, BorderLayout.PAGE_END);
this.add(textarea, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(button)) {
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(textarea.getText().replaceAll("\n", "\r\n"));
fileWriter.close();
JOptionPane.showMessageDialog(this,
"テキストを" + file.getName() + "に保存しました。");
} catch(Exception e) {}
}
}
}
}

0 件のコメント: