-2

我没有把我所有的课程都放在这里,但这里是:

检查选项面板

package main;

import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class CheckOptionsPanel extends JFrameL implements Serializable {

    public static CheckingAccount account;
//    static void chooseFile(int i) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//    }
    private JPanel panel;
    private JLabel title;
    private JRadioButton enterTrans;
    private JRadioButton listTrans;
    private JRadioButton listChecks;
    private JRadioButton listDep;
    private JRadioButton readFile;
    private JRadioButton writeFile;
    private ButtonGroup radioButtonGroup;  // To group radio buttons
    //
    private static String filePath;
    public static boolean changeInAcc;
    //
    private int transCode, checkNumber;
    private double transAmount, chargeAmount;
    private String transCodeStr, transAmountStr, message, checkNumberStr, serviceCharge = "svc.chrg.";
    private String transType;//Check or deposit
    private int chargedNum = 0; //number of times charged for having balance below $500
    private double finalBalance;
    /**
     * ********************************************************
     */
    private final int WINDOW_WIDTH = 400;
    private final int WINDOW_HEIGHT = 150;

    //Constructor
    public CheckOptionsPanel(CheckingAccount acc) {

        account = acc;
        setTitle("Checking Account Actions");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        buildPanel();
        //adding panel to frame's content pane
        add(panel);
        //display
        //setBackground(Color.GREEN);
        setVisible(true);

    }

    private void buildPanel() {
        enterTrans = new JRadioButton("Enter transaction");
        enterTrans.setBackground(Color.GREEN);
        listTrans = new JRadioButton("List all Transactions");
        listTrans.setBackground(Color.GREEN);
        listChecks = new JRadioButton("List all Checks");
        listChecks.setBackground(Color.GREEN);
        listDep = new JRadioButton("List all Deposits");
        listDep.setBackground(Color.GREEN);
        readFile = new JRadioButton("Read from file");
        readFile.setBackground(Color.GREEN);
        writeFile = new JRadioButton("Write to the file");
        writeFile.setBackground(Color.GREEN);

        title = new JLabel("Choose action:\n");
        title.setFont(new Font("Helvetica", Font.BOLD, 24));
        setBackground(Color.GREEN);

        //Group RadioButtons
        radioButtonGroup = new ButtonGroup();
        radioButtonGroup.add(enterTrans);
        radioButtonGroup.add(listTrans);
        radioButtonGroup.add(listChecks);
        radioButtonGroup.add(listDep);
        radioButtonGroup.add(readFile);
        radioButtonGroup.add(writeFile);


        //adding listeners to radio buttons
        enterTrans.addActionListener(new RadioButtonListener());
        listTrans.addActionListener(new RadioButtonListener());
        listChecks.addActionListener(new RadioButtonListener());
        listDep.addActionListener(new RadioButtonListener());
        readFile.addActionListener(new RadioButtonListener());
        writeFile.addActionListener(new RadioButtonListener());


        //create panel
        panel = new JPanel();
        panel.add(title);
        panel.add(enterTrans);
        panel.add(listTrans);
        panel.add(listChecks);
        panel.add(listDep);
        panel.add(readFile);
        panel.add(writeFile);

//setBackground(Color.GREEN);

    }

    //raidiButtonListener              
    private class RadioButtonListener implements ActionListener {

        DecimalFormat formatter = new DecimalFormat("0.00");

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == enterTrans) {
                boolean transException;
                do {
                    transException = false;
                    try {
                        do {

                            transCodeStr = JOptionPane.showInputDialog("Enter trans code:");
                            transCode = Integer.parseInt(transCodeStr);
                            if (transCode != 0 && transCode != 1 && transCode != 2) {
                                String message = "Invalid input!\nPlease enter 1 for Check, 2 for Deposit or 0 to exit the "
                                        + "Please try again:";
                                JOptionPane.showMessageDialog(null, message);
                            }
                        } while (transCode != 0 && transCode != 1 && transCode != 2);
                    } catch (NumberFormatException ep) {

                        JOptionPane.showMessageDialog(null, "Wrong input format!\nTry again:");
                        transException = true;
                    }

                } while (transException == true);
                if (transCode == 1) {
                    boolean checkException;
                    do {
                        checkException = false;
                        try {
                            checkNumberStr = JOptionPane.showInputDialog("Enter the check number:");
                            checkNumber = Integer.parseInt(checkNumberStr);
                        } catch (NumberFormatException nfe) {
                            JOptionPane.showMessageDialog(null, "Wrong input format!\nTry again:");
                            checkException = true;
                        }

                    } while (checkException == true);
                }

                if (transCode != 0) {
                    boolean amtException;
                    do {
                        amtException = false;
                        try {
                            do {
                                transAmountStr = JOptionPane.showInputDialog("Enter trans amt:");
                                transCode = Integer.parseInt(transCodeStr);
                                transAmount = Double.parseDouble(transAmountStr);
                                if (transAmount < 0) {
                                    String message = "Invalid input!\nTransaction amount must be a positive number.\n"
                                            + "Please try again:";
                                    JOptionPane.showMessageDialog(null, message);
                                }
                            } while (transAmount < 0);
                        } catch (NumberFormatException ae) {
                            JOptionPane.showMessageDialog(null, "Wrong input format!\nTry again:");
                            amtException = true;
                        }

                    } while (amtException == true);
                    account.setBalance(transAmount, transCode);
                    account.setServiceCharge(transAmount, transCode);

                    if (transCode == 1) {
                        transType = "Check";
                        chargeAmount = 0.15;
                        //create transaction abject for check
                        Transaction checkTrans = new Check(checkNumber, account.getTransCount(), transAmount, transType);
                        account.addTrans(checkTrans);
                        //increment number of transactions
                        account.setTransCount();
                        // create transaction object for service charge
                        account.addTrans(account.getTransCount(), chargeAmount, serviceCharge);
                        account.setTransCount();
                    } else {
                        transType = "Deposit";
                        chargeAmount = 0.10;
                        account.addTrans(account.getTransCount(), transAmount, transType);
                        account.setTransCount();
                        account.addTrans(account.getTransCount(), chargeAmount, serviceCharge);
                        account.setTransCount();
                    }


                    message = account.getName() + "'s account\n" + "Transaction: ";
                    if ("Check".equals(transType)) {
                        message += transType + " #" + checkNumber + " in amount of $";
                    } else {
                        message += transType + " in amount of $";
                    }
                    message += formatter.format(transAmount) + " \nCurrnet Balance: $"
                            + formatter.format(account.getBalance())
                            + " \nService Charge: " + transType + " --- charge $"
                            + formatter.format(chargeAmount);

                    if (account.warningMessage()) {
                        message += " \nWarning: Balance below $50";
                    }
                    if (account.negativeBalance()) {
                        message += " \nService charge: Below $0 --- charge: $10.00";
                        account.addTrans(account.getTransCount(), 10, serviceCharge);
                        account.setTransCount();
                    }
                    if (account.belowBalanceCheck() && account.getbelow500Charge() && chargedNum == 0) {
                        message += " \nService Charge: Below $500 --- charge: $5.00";
                        chargedNum++;
                        account.addTrans(account.getTransCount(), 5, serviceCharge);
                        account.setTransCount();
                    }
                    message += " \nTotal Service Charge: $" + formatter.format(account.getServiceCharge());
                    JOptionPane.showMessageDialog(null, message);
                } else {

                    finalBalance = account.getBalance() - account.getServiceCharge();
                    message = account.getName() + "'s account\n" + "Transaction : End" + " \nCurrnet Balance:  ($"
                            + formatter.format(account.getBalance()) + ")" + " \nTotal Service Charge:  $"
                            + formatter.format(account.getServiceCharge())
                            + "\nFinal Balance:  ($" + finalBalance + ")";
                    JOptionPane.showMessageDialog(null, message);
                }
                changeInAcc = true;
                /*Endof enterTrans*/            } else if (e.getSource() == listTrans) {

                account.getAllTransReport();

            } else if (e.getSource() == listChecks) {
                account.CheckSort();
            } else if (e.getSource() == listDep) {
                account.DepSort();
            } else if (e.getSource() == writeFile) {
                chooseFile(2);
                try {

                    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
                    out.writeObject(account);
                    out.close();
                } catch (IOException exc) {
                    exc.getMessage();
                }
            } else {
                chooseFile(1);
                try {
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
                    account = (CheckingAccount) in.readObject();

                    in.close();

                } catch (ClassNotFoundException ex) {
                    JOptionPane.showMessageDialog(null, "Class not found in this file", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (ClassCastException ex) {
                    JOptionPane.showMessageDialog(null, "Unable to cast file", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (InvalidClassException ex) {
                    JOptionPane.showMessageDialog(null, "Invalid class", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (EOFException ex) {
                    JOptionPane.showMessageDialog(null, "File is empty", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (StreamCorruptedException ex) {
                    JOptionPane.showMessageDialog(null, "File is Corrupted", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (FileNotFoundException ex) {
                    JOptionPane.showMessageDialog(null, "File not found", "warning", JOptionPane.WARNING_MESSAGE);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, e);
                }
            }

        }
    }

    public static void chooseFile(int ioOption) {
        int status;
        JFileChooser chooser = new JFileChooser();
        if (ioOption == 1) {
            status = chooser.showOpenDialog(null);
        } else {
            status = chooser.showSaveDialog(null);
        }

        if (status == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            filePath = file.getPath();
        }
        changeInAcc = false;
    }
}

框架

哪个控制退出按钮。

package main;
import javax.swing.*;
import java.awt.event.*;
public class JFrameL extends JFrame
{
    /** Creates a new instance of JFrameL */
    public JFrameL() {
        //super(title);
        JFrameL.FrameListener listener = new JFrameL.FrameListener();
        addWindowListener(listener);
    }
   private class FrameListener extends WindowAdapter
   {
    public void windowClosing(WindowEvent e) {
            //This will only be seen on standard output.
       //System.out.println("WindowListener method called:");
       if(CheckOptionsPanel.changeInAcc ==true){
       CheckOptionsPanel.chooseFile(2);
       }
          setVisible(false);
          System.exit(0);
    }
   }   
}

当我点击Exit它时实际上打开了保存窗口,我输入正在保存的文件的名称,它似乎工作正常,但文件实际上并没有保存在我的计算机中。

问题是,ChooseFile()当我手动保存文件时,该方法工作得非常好,这意味着我点击了“写入文件”按钮......但是当点击退出按钮时,它不会真正保存我的文件。

任何想法为什么它不保存?

4

1 回答 1

2

chooseFile没有 I/O。它允许用户选择和归档并且什么都不做......

public static void chooseFile(int ioOption) {
    int status;
    JFileChooser chooser = new JFileChooser();
    if (ioOption == 1) {
        status = chooser.showOpenDialog(null);
    } else {
        status = chooser.showSaveDialog(null);
    }

    if (status == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        filePath = file.getPath();
    }
    changeInAcc = false;
}

与您的“写入”选项相比...

chooseFile(2);
try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
    out.writeObject(account);
    out.close();
} catch (IOException exc) {
    exc.getMessage();
}

一句警告。以这种方式依赖static变量只会炸毁你的脸。该chooseFile方法应该返回File被选择的。

您应该自己创建一个readandwrite方法来执行这些操作并允许您根据需要(从类的实例)访问它们......

我看不出你是如何神奇地想象调用该chooseFile方法实际上会突然保存任何东西......

添加

谢谢安德鲁...

您的异常处理还有一些不足之处。至少付出努力的分数。如果你想显示错误消息,你应该使用Exception#printStackTrace它会自动将堆栈跟踪转储到标准输出,让你的生活变得更简单......

chooseFile(2);
try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
    out.writeObject(account);
    out.close();
} catch (IOException exc) {
    //exc.getMessage(); <-- This is useless
    exc.printStackTrace();
}
于 2013-05-10T03:49:28.790 回答