当单击一个按钮时,我的代码应该创建一个.txt文件 - 但它没有。为什么?

时间:2018-02-27 23:20:01

标签: java swing outputstream

包kebek;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Kebek extends JFrame implements ActionListener {

String mainFileName; // the file name the user entered
String essay; // the data the user wrote in the text field

public Kebek() {
    // set up the title of the frame
    super("Kebek Text Editor");
    //or setTitle("Kebek Text Editor");

    //must be added to customize apeariance
    this.setLookAndFeel();

    // set the size of the frame - in px
    this.setSize(500, 1000);
    // or pack();   - this The pack() method sets the frame big enough
    //to hold the preferred size of
    //each component inside the frame (but no bigger)

    // exits the program when x button is clicked
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Choose layout to give to our frame
    FlowLayout flo = new FlowLayout();

    // associate the manager with the container.
    this.setLayout(flo);

    // creating save button and adding it into layout
    JButton saveButton = new JButton("Save");
    // make save button listen for button clicks
    saveButton.addActionListener(this);

    JButton openButton = new JButton("Open");
    openButton.addActionListener(this);

    this.add(saveButton);
    this.add(openButton);

    // create text fields and add them to our layout
    JLabel fileNameLabel = new JLabel("file name: ", JLabel.RIGHT);
    JTextField fileNameText = new JTextField(20);

    // create writing area
    JTextArea editSpace = new JTextArea(40, 40);
    String editSpaceText = editSpace.getText();

    this.add(fileNameLabel);
    this.add(fileNameText);

    this.add(editSpace);

    //
    String fileNameStr = fileNameText.getText();

    //
    this.essay = editSpaceText;
    this.mainFileName = fileNameStr;

    // makes the frame visible
    this.setVisible(true);

}

// needed for to customize our frame
private void setLookAndFeel() {
    try {
        UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (Exception exc) {
        // do nothing
    }

}

// save file method

public void saveFile() {
    try {

        // write the string on to a file
        FileWriter writeFile = new FileWriter(this.mainFileName + ".txt");
        BufferedWriter buffWrite = new BufferedWriter(writeFile);

        buffWrite.write(this.essay);

        buffWrite.close();

    } catch (IOException ex) {
        System.out
                .println("There is an error with the" + this.mainFileName);
    }
}

// action performed method - event handler
@Override
public void actionPerformed(ActionEvent event) {
    // listen to what button is pressed
    String cmd = event.getActionCommand();
    this.saveFile();

    //        // if save button is pressed save file
    //        if (cmd.equals("save")) {
    //            System.out.println(" This is the result of cmd" + cmd);
    //
    //            // if the open button is presses open file
    //            this.saveFile();
    //        } else if (cmd.equals("open")) {
    //
    //            // else do nothing
    //        } else {
    //
    //        }
}

public static void main(String[] argus) {
    Kebek kebekframe = new Kebek();

}

}

我想要做的是当按下保存按钮时,会创建一个带有用户选择文件名的.txt文件(来自fileNameStr的字符串)。该文件应包含他们在我提供的文本字段(editSpaceText)中键入的单词。此外,当我运行此代码时,它不会给我一个错误。很可能问题出在我的saveFile& actionPreformed方法。

2 个答案:

答案 0 :(得分:1)

您没有在相关时间点将JTextArea的内容分配给变量essay - 您在构造函数中指定它,但JTextArea可能为空。< / p>

JTextArea的文字与essay变量

之间没有神奇的联系

您需要做的第一件事是将相关组件提供给班级的其他部分,方法是将它们作为实例字段...

public class Kebek extends JFrame implements ActionListener {

    private JTextArea editSpace;
    private JTextField fileNameText;

    public Kebek() {
        //...
        JLabel fileNameLabel = new JLabel("file name: ", JLabel.RIGHT);
        fileNameText = new JTextField(20);

        // create writing area
        editSpace = new JTextArea(40, 40);
        // pointless
        //String editSpaceText = editSpace.getText();

        this.add(fileNameLabel);
        this.add(fileNameText);

        this.add(editSpace);

        // pointless
        //String fileNameStr = fileNameText.getText();

        // point less
        //this.essay = editSpaceText;
        //this.mainFileName = fileNameStr;

        //...

    }

然后,当您需要这些组件的值时,您需要它们......

public void saveFile() {
    String mainFileName = fileNameText.getText();
    String essay = editSpace.getText();
    try (BufferedWriter buffWrite = new BufferedWriter(new FileWriter(mainFileName + ".txt")))  {

        // write the string on to a file
        buffWrite.write(essay);

    } catch (IOException ex) {
        System.out
                .println("There is an error with the" + mainFileName);
    }
}

您还应该查看try-with-resources statement以获得更好的资源管理方式

答案 1 :(得分:0)

尝试使用此..

File file=new File(this.mainFileName + ".txt");
if(file.exists()==false){
   file.createNewFile();
}
FileWriter writeFile = new FileWriter(file);
BufferedWriter buffWrite = new BufferedWriter(writeFile);