解答例 - 実習課題1 - 1.テキストファイルの入出力
(実習課題1)
以下の機能を持つ簡易エディターを作成しなさい。
- 任意のファイルを開くことができる。
- 「カット」「コピー」「ペースト」の機能を持つ。
解答例
/**
* SimpleEditorExample.java
* TECHSCORE Java 入出力1章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.io.chapter1.exercise1;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultEditorKit.CopyAction;
import javax.swing.text.DefaultEditorKit.CutAction;
import javax.swing.text.DefaultEditorKit.PasteAction;
public class SimpleEditorExample extends JFrame implements ActionListener {
private JTextArea textArea = new JTextArea();
//カット、コピー、ペースト用アクション
private Action cutAction = new CutAction();
private Action copyAction = new CopyAction();
private Action pasteAction = new PasteAction();
private JButton open = new JButton("開く");
private JButton cut = new JButton(cutAction);
private JButton copy = new JButton(copyAction);
private JButton paste = new JButton(pasteAction);
private JFileChooser chooser = new JFileChooser();
//コンストラクタ
public SimpleEditorExample() {
super("簡易エディタ");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
getContentPane().add(panel1, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
getContentPane().add(panel2, BorderLayout.SOUTH);
panel1.add(open);
panel2.add(cut);
panel2.add(copy);
panel2.add(paste);
open.addActionListener(this);
}
public static void main(String[] args) {
new SimpleEditorExample().setVisible(true);
}
//[開く]ボタンが押されたときの処理
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(open)) {
openFile();
}
}
//ファイルを開くメソッド
private void openFile() {
int returnVal = chooser.showOpenDialog(this);
try {
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
FileReader reader = new FileReader(file);
textArea.read(reader, null);
setTitle(file.getAbsolutePath());
reader.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

