使用ActionListener使用Formatter写入文件(JAVA)时出错

时间:2016-03-27 21:47:49

标签: java file actionlistener formatter file-writing

所以我创建了一个充当日志的程序,Journal对象应该创建一个CreateFile对象,它将创建一个文件,并从JTextArea写入文本输入,并关闭文件。(基本上保存文件)。每当用户按下保存按钮时,它都应该这样做。

现在所有发生的事情都会创建一个空白文件。除写入文件外的所有内容都有效。请帮助识别并更正写入我的文件时的错误,下面是我的代码。

这是Journal Class

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Formatter;

import javax.swing.*;
public class Journal extends JFrame{
private JTextField date;
public JTextArea entry;
private JButton button;
public static String day, month, year;
private Formatter formatter;
        public Journal(String month, String day, String year){
            this.day=day;
            this.month=month;
            this.year=year;
        //Use parameter so display a date
            String theDate =  month + "/ "+day+"/ "+year;
            Font theFont = new Font("Serif",Font.BOLD,20);
        setLayout(new BorderLayout());
        date = new JTextField(theDate+ "     "+"Journal Entry");
        date.setFont(theFont);
        date.setSize(new Dimension(500,50));
        date.setEditable(false);
        //Create a save Button
        button = new JButton("Save Entry");

        add(button,BorderLayout.WEST);
        //Create a place to write the journal entry
        entry = new JTextArea("Enter your entry here");
        entry.setLineWrap(true);
        Font JTFFont = new Font("Serif",Font.PLAIN,14);
        entry.setFont(JTFFont);
        Handlerclass handler = new Handlerclass();
        button.addActionListener(handler);
        add(date,BorderLayout.NORTH);
        add(entry,BorderLayout.CENTER);
        }
private class Handlerclass implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {

        try {

         CreateFile cf = new CreateFile(month,day,year);
         cf.openFile();
         cf.addRecords();
         cf.closeFile();



        }
        catch(Exception error){
            System.out.println("You have an error");
        }
    }

    }
    public void closeFile(){
        formatter.close();
    }
}

这是CreateFile类

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile extends Journal{

    public CreateFile(String month, String day, String year) {
        super(month, day, year);
        // TODO Auto-generated constructor stub
    }

    private Formatter x;

    public void openFile(){
        try{
            String date = String.format("%s_%s_%s.txt", this.month, this.day, this.year);
            x = new Formatter(date);
        }
        catch(Exception e)
        {

            System.out.println("you have an error");
    }
    }
    public void closeFile(){
        x.close();
    }
    public void addRecords(){

        entry.addKeyListener(
                new KeyListener(){

                    @Override
                    public void keyTyped(KeyEvent e) {
                        // TODO Auto-generated method stub
                        x.format(entry.getText());
                    }

                    @Override
                    public void keyPressed(KeyEvent e) {}

                    @Override
                    public void keyReleased(KeyEvent e) {}
                }
                );

    }
}

这是主要的课程

import java.awt.Color;

import javax.swing.*;

public class MainClass {
    public static void main(String args[]){
        //Create new Journal Entry
Journal j = new Journal("3","27","2016");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
j.setSize(500, 500);
j.setResizable(false);
j.getContentPane().setBackground(Color.WHITE);
    }
}

1 个答案:

答案 0 :(得分:1)

您的实现中的主要问题是,方法CreateFile::addRecords不会写入文件。仅注册KeyListener。之后,Formatter立即关闭。现在尝试在每个按键上写入文件,但这是不可能的,因为Formatter已关闭。

其他建议:在异常捕获中打印Stacktrace(err.printStackTrace)要好得多。所以你能够找到,出了什么问题以及在哪里。

下一点(CreateFile延长Journal):有时最好使用Strategy Patternseparate concerns并避免使用子类。

这是一个修复问题并遵守其他要点的实现:



import java.awt.*;
import java.io.FileNotFoundException;
import javax.swing.*;
public class Journal extends JFrame{
    public Journal(String month, String day, String year){
        String theDate =  month + "/ "+day+"/ "+year;
        Font theFont = new Font("Serif",Font.BOLD,20);
        setLayout(new BorderLayout());
        JTextField dateField = new JTextField(theDate+ "     "+"Journal Entry");
        dateField.setFont(theFont);
        dateField.setSize(new Dimension(500,50));
        dateField.setEditable(false);
        JButton button = new JButton("Save Entry");
        JTextArea entry = new JTextArea("Enter your entry here");
        entry.setLineWrap(true);
        Font JTFFont = new Font("Serif",Font.PLAIN,14);
        entry.setFont(JTFFont);
        String date = String.format("%s_%s_%s.txt", month, day, year);
        try {
            button.addActionListener(new SaveHandler(date, entry));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        add(button,BorderLayout.WEST);
        add(dateField,BorderLayout.NORTH);
        add(entry,BorderLayout.CENTER);
    }
}






import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.Formatter;

class SaveHandler implements ActionListener {

    private String date;
    private JTextArea entry;
    public SaveHandler(String date, JTextArea entry) throws FileNotFoundException {
        this.date = date;
        this.entry = entry;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            new Formatter(date).format(entry.getText()).close();
        } catch (FileNotFoundException err) {
            err.printStackTrace();
        }
    }
}