うめすこんぶ

日々のプログラミングで残しておきたいメモ.何かの役に立てれば幸いです.

「SwingDesigner」でSwingアプリケーションをつくろう! その5~ファイルを保存する

スポンサーリンク

前回の続きです. 今回は,エディタで編集したテキストファイルをちょろっとコードを書いて,保存してみましょう. 簡単ですよ.

今回のポイント
  • FileChooserクラスのshowSaveDialogメソッドで保存ダイアログを表示します

ファイルハンドラのクラスを利用して保存処理をする.

javaでファイル操作するクラス作った~読み込みと書き込みを手っ取り早く… - プログラミングのメモに書いたファイルハンドラのwriteを使います.

とりあえず,前回を参考にボタンを配置して,コンポーネントから,「新規」のアクションをボタンにセットする.

新しく定義されたクラスSwingAction_1の中の,actionPerformed(ActionEvent e)を以下のように書きます.

public void actionPerformed(ActionEvent e) {
    JFileChooser filechooser = new JFileChooser(); // ファイル選択用クラス
    int selected = filechooser.showSaveDialog(frmTexteditor); //「保存」ダイアログ表示
    if (selected == JFileChooser.APPROVE_OPTION){ //ファイルが選択されたら
        File file = filechooser.getSelectedFile();
        FileHandler.write(file.getPath(), textArea.getText()); //書き込み
     }
}

実際の処理は,filechooser.showSaveDialog(frmTexteditor)で保存ダイアログを表示します. ダイアログの「保存」ボタンを押すと,選択されたファイルの情報がfilechooser.getSelectedFile(); で取得され,FileHandler.write(file.getPath(), textArea.getText());でファイルにテキストエリアに書かれた文字が書き込まれます.常に新規書き込みになるので注意.

また,ボタンの上にアクションの名前がかぶってしまうので,アクションの名前を変更. SwingAction_1のコンストラクタ内を下のように変更.

public SwingAction_1() {
    putValue(NAME, "保存"); //名前を変更
    putValue(SHORT_DESCRIPTION, "Some short description");
}

今回のソース

package swingTest;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class TextEditorApp {

    private JFrame frmTexteditor; 
    private JLabel lblNewLabel; // ラベルの追加
    private JButton btnNewButton; //ボタンの追加
    private final Action action = new SwingAction(); //アクション追加
    private JScrollPane scrollPane; // スクロールするエリアを追加
    private JTextArea textArea; //テキスト表示エリアを追加
    private JButton button;
    private final Action action_1 = new SwingAction_1();
    /**
    * Launch the application.
    */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TextEditorApp window = new TextEditorApp();
                    window.frmTexteditor.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
    * Create the application.
    */
    public TextEditorApp() {
        initialize();
    }

    /**
    * Initialize the contents of the frame.
    */
    private void initialize() {
        frmTexteditor = new JFrame();
        frmTexteditor.setTitle("TextEditor");
        frmTexteditor.setBounds(100, 100, 450, 300);
        frmTexteditor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmTexteditor.getContentPane().setLayout(null);
        
        lblNewLabel = new JLabel("ファイル名"); // ラベルを初期化
        lblNewLabel.setBounds(12, 13, 195, 13);
        frmTexteditor.getContentPane().add(lblNewLabel);
        
        btnNewButton = new JButton(); // ボタンを初期化
        btnNewButton.setText("開く");
        btnNewButton.setBounds(221, 9, 91, 21);
        btnNewButton.setAction(action);  // ボタンにアクションを設定
        frmTexteditor.getContentPane().add(btnNewButton);
        
        scrollPane = new JScrollPane(); 
        scrollPane.setBounds(124, 36, 298, 216);
        frmTexteditor.getContentPane().add(scrollPane);
        
        textArea = new JTextArea();
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);
        scrollPane.setViewportView(textArea);
        
        button = new JButton("保存");
        button.setAction(action_1);
        button.setBounds(331, 9, 91, 21);
        frmTexteditor.getContentPane().add(button);
        
    }

    private class SwingAction extends AbstractAction {
        public SwingAction() {
            putValue(NAME, "開く"); //名前を変更
            putValue(SHORT_DESCRIPTION, "Some short description");
        }
        public void actionPerformed(ActionEvent e) {
            JFileChooser filechooser = new JFileChooser(); // ファイル選択用クラス

            int selected = filechooser.showOpenDialog(frmTexteditor); //「開く」ダイアログ表示
            if (selected == JFileChooser.APPROVE_OPTION){ //ファイルが選択されたら
                File file = filechooser.getSelectedFile(); 
                lblNewLabel.setText(file.getName()); //ラベルの文字をファイル名に
                textArea.setText(FileHandler.read(file.getPath())); //ファイルの中身を表示
             }
        }
    }
    private class SwingAction_1 extends AbstractAction {
        public SwingAction_1() {
            putValue(NAME, "保存"); //名前を変更
            putValue(SHORT_DESCRIPTION, "Some short description");
        }
        public void actionPerformed(ActionEvent e) {
            JFileChooser filechooser = new JFileChooser(); // ファイル選択用クラス

            int selected = filechooser.showSaveDialog(frmTexteditor); //「保存」ダイアログ表示
            if (selected == JFileChooser.APPROVE_OPTION){ //ファイルが選択されたら
                File file = filechooser.getSelectedFile();
                FileHandler.write(file.getPath(), textArea.getText()); //書き込み
             }
        }
    }
}