1

好的,首先......是的,这是一个家庭作业问题。我被困住了。我已经能够创建 .txt 文件并将数据从 GUI 文本字段保存到其中。只要我不退出 GUI,它将继续添加到文件中。一旦我再次启动它,下次我保存任何内容时,整个文件都会被覆盖(单击 GUI 上的保存按钮)。我想做的是:

-从 GUI 文本字段输入数据 -单击保存按钮(创建文件并应该将数据附加到 .txt 文件) -能够从文件读取回面板 -能够关闭和重新打开 GUI 并根据需要附加 .txt 文件

我很接近,但我正在做一些我害怕的愚蠢的事情。下面是我的 GUI、CreateTextFile 和 ReadTextFile 的 java 代码

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.*;

public class DonorGUI extends JFrame
{

    // Components
    private JPanel panel;
    private JTextArea results;
    private JButton entryButton;
    private JButton exitButton;
    private JButton clearButton;
    private JButton saveButton;
    private JButton openButton;
    private JTextField donorField;
    private JTextField charityField;
    private JTextField pledgeField;

    //create variables
    String[] donorName = new String[20];
    String[] charityName = new String[20];
    double[] donationAmt = new double[20];
    int i = 0;


    // Constants for the window size
    private final int WINDOW_WIDTH = 750;
    private final int WINDOW_HEIGHT = 525;

    //Constructor
    public DonorGUI(){

        // Set the title.
        setTitle("Wounded Warrior Donation Tracker.");

        // Specify what happens when the close button is clicked.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Build the panel that contains the other components.
        buildPanel();

        // Add the panel to the content pane.
        add(panel);

        // Size and display the window.
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setVisible(true);
    }

    //The buildPanel method creates a panel containing other components.
    private void buildPanel(){

        // Create labels to display instructions.
        JLabel message1 = new JLabel("Name of the Donor:");
        JLabel message2 = new JLabel("Name of the Charity:");
        JLabel message3 = new JLabel("Amount of the Pledge:");

        //instantiate the results area
        results = new JTextArea(25,60);
        results.setEditable(false);
        results.setWrapStyleWord(true);
        results.setLineWrap(true);
        results.setBorder(BorderFactory.createLoweredBevelBorder());


        // Create text fields to receive user input
        donorField = new JTextField(10);
        charityField = new JTextField(10);
        pledgeField = new JTextField(10);


        //create the user buttons to cause action
        entryButton = new JButton("Enter Donation.");
        entryButton.addActionListener(new EntryButtonListener());
        exitButton = new JButton("EXIT");
        exitButton.addActionListener(new ExitButtonListener());
        clearButton = new JButton ("Clear Fields");
        clearButton.addActionListener(new ClearButtonListener());
        saveButton = new JButton ("Save");
        saveButton.addActionListener(new SaveButtonListener());
        openButton = new JButton ("Open");
        openButton.addActionListener(new OpenButtonListener());

        // Create a panel.
        panel = new JPanel();
        panel.setBackground(Color.orange);

        //set the LayoutManager
        panel.setLayout(new FlowLayout());

        // Add the labels, text fields, and button to the panel.
        panel.add(message1);
        panel.add(donorField);
        panel.add(message2);
        panel.add(charityField);
        panel.add(message3);
        panel.add(pledgeField);
        panel.add(results);
        panel.add(entryButton);
        panel.add(clearButton);
        panel.add(saveButton);
        panel.add(openButton);
        panel.add(exitButton);      
    }
    private class EntryButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            donorName[i] = donorField.getText();
            charityName[i] = charityField.getText();
            if (donationAmt(pledgeField.getText())) {
                  donationAmt[i] = Double.parseDouble(pledgeField.getText());
            }else{
                donorField.setText("");
                charityField.setText("");
                pledgeField.setText("");
            }
            results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
            donorField.setText("");
            charityField.setText("");
            pledgeField.setText("");
            i++;
        } 
    }
    public boolean donationAmt(String amount) {

        if(amount==null || amount=="" || amount.length()<1){  //checking for empty field
            JOptionPane.showMessageDialog(null, "Please enter amount pledged");
            return false;
        }
        for(int i = 0; i < amount.length(); i++){  //verifying dollar amount entered as number
                if (!Character.isDigit(amount.charAt(i)) && amount.charAt(i)!='.'){ 
                    JOptionPane.showMessageDialog(null, "Invalid input.");
                    return false;
                } 
        }
        return true;

    }  
    private class ClearButtonListener implements ActionListener {

        public void actionPerformed (ActionEvent e) {
            donorField.setText("");
            charityField.setText("");
            pledgeField.setText("");
            }
    }
    private class ExitButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }
    private class SaveButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            CreateTextFile cr = new CreateTextFile();
            cr.openFile();
            cr.addRecords(donorName, charityName, donationAmt);
            cr.closeFile();

            JavaDBClass db = new JavaDBClass();



        }

    }
    private class OpenButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            ReadTextFile read = new ReadTextFile();
            read.openFile();
            DonorGUI donor = read.readRecords();
            read.closeFile();           
            JavaDBClass db = new JavaDBClass(donor);
            for(int i = 0;i<donor.donationAmt.length;i++){

                try {
                    results.append(db.showTable()[i]+"\n");
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        }

    }

    /* Application method */
    public static void main(String[] args){

        DonorGUI rpc = new DonorGUI();
    }
}

创建文本文件 JAVA 代码:

/** This will create a text file based on user input and save it as donations.txt.
 * 
 */
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;

public class CreateTextFile {

    //object that outputs text to a file
    private Formatter output;

    //try opening a file
    public void openFile(){

        try
        {
            output = new Formatter("C:/PRG421_Data/donations.txt");
        }
        catch (SecurityException securityException)
        {
            System.out.println("You cannot write to this file.");
        }
        catch (FileNotFoundException notFoundException)
        {
            System.out.println("You couldn't open or find the file.");
        }

    }
    //try writing to the file
    public void addRecords(String[] donor, String[] charity, double[] donation){

                try{
                     for (int j=0; j<donor.length; j++) {
                         if (donor[j] != null) {
                            output.format("\n%s %s %.2f",donor[j],charity[j],donation[j]);

                           }
                     }
              }

              catch (FormatterClosedException formatterClosedException){

                     System.out.println("You couldn't write to this file.");

              }

              catch (NoSuchElementException elementException){

                     System.out.println("Invalid Input.");

              }

       }
    //try closing the file
    public void closeFile(){
        if(output!=null)
            output.close();
    }
}

阅读文本文件 JAVA 代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadTextFile {

    private Scanner input;

    //try to open the file
    public void openFile(){
        try{
            input = new Scanner(new File("C:/PRG421_Data/donations.txt"));
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            System.out.println("File not found.");
            System.exit(1);
        }
    }
    //try to read from the file
    public DonorGUI readRecords(){

        DonorGUI gui = new DonorGUI();

        while(input.hasNext())
        {
            for(int j = 0;j<20;j++){
            gui.donorName[j] = input.next();
            gui.charityName[j] = input.next();
            gui.donationAmt[j] = input.nextDouble();
            }
        }
        return gui;

    }
    //try to close the file
    public void closeFile(){
        if(input!=null)
            input.close();

    }
}
4

2 回答 2

5

代替

 output = new Formatter("C:/PRG421_Data/donations.txt");

利用

output = new Formatter(new FileOutputStream("C:/PRG421_Data/donations.txt", true));

参数表示true追加。

于 2012-06-05T02:55:16.063 回答
4
output = new Formatter("C:/PRG421_Data/donations.txt");

AFAIU 这将覆盖现有的File. 而不是 a String,构造函数需要OuputStream打开的 a 来追加

于 2012-06-05T02:52:04.420 回答