4 つのテキスト フィールドとテキスト エリアの内容を保存し、[送信] ボタンをクリックするとテキスト ファイルに保存するプログラムに取り組んでいます。出力は次のようになります。
To: [Text Field]
CC: [Second Text Field]
Bcc: [Third Text Field]
Subject: [Fourth Text Field]
Message:
[Text Area]
たとえば、テキスト ファイルの最初の行には、テキスト フィールドの内容である "To: " があり、次の行にスキップします。
プログラムはコンパイルされますが、テキスト ファイルは空白のままです。考えられる限りのことを試してみましたが、原因がわかりません。これが私のコードです:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class EmailProg extends JFrame implements ActionListener {
private JPanel panNorth;
private JPanel panCenter;
private JPanel panSouth;
private JLabel toLabel;
private JLabel ccLabel;
private JLabel bccLabel;
private JLabel subLabel;
private JLabel msgLabel;
private JTextField toField;
private JTextField ccField;
private JTextField bccField;
private JTextField subField;
private JTextArea msgArea;
private JButton send;
public EmailProg() {
setTitle("Compose Email");
setLayout(new BorderLayout());
panNorth = new JPanel();
panNorth.setLayout(new GridLayout(4, 2));
JLabel toLabel = new JLabel("To:");
panNorth.add(toLabel);
JTextField toField = new JTextField(15);
panNorth.add(toField);
JLabel ccLabel = new JLabel("CC:");
panNorth.add(ccLabel);
JTextField ccField = new JTextField(15);
panNorth.add(ccField);
JLabel bccLabel = new JLabel("Bcc:");
panNorth.add(bccLabel);
JTextField bccField = new JTextField(15);
panNorth.add(bccField);
JLabel subLabel = new JLabel("Subject:");
panNorth.add(subLabel);
JTextField subField = new JTextField(15);
panNorth.add(subField);
add(panNorth, BorderLayout.NORTH);
panCenter = new JPanel();
panCenter.setLayout(new GridLayout(2, 1));
JLabel msgLabel = new JLabel("Message:");
panCenter.add(msgLabel);
JTextArea msgArea = new JTextArea(5, 15);
panCenter.add(msgArea);
add(panCenter, BorderLayout.CENTER);
panSouth = new JPanel();
panSouth.setLayout(new FlowLayout());
JButton send = new JButton("Send");
send.addActionListener(this);
panSouth.add(send);
add(panSouth, BorderLayout.SOUTH);
}
public void actionPerformed (ActionEvent event) {
try {
//Write labels and corresponding fields to text file
BufferedWriter outfile = new BufferedWriter(new FileWriter("email.txt"));
outfile.write("To: ");
outfile.write(toField.getText());
//repeat for CC, Bcc, and Subject labels/fields, and for Message label/text area
}
catch(FileNotFoundException e) {
System.out.println("File not found.");
}
catch(NullPointerException j){
System.out.println("Null.");
}
catch(IOException k){
System.out.println("IO Exception.");
}
JOptionPane.showMessageDialog(this,"Saved");
}
public static void main(String[] args) {
EmailProg win = new EmailProg();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.pack();
win.setVisible(true);
}
}
よろしくお願いいたします。