打开文件后的Java GUI刷新结果

时间:2015-06-05 09:27:29

标签: java swing jfilechooser jformattedtextfield

我正在尝试制作所得税计算器,我有一个带有菜单栏的MainWindow来打开文件。在我用JFileChooser打开并解析文件后,我将结果放在Taxpayer类中。问题是读取文件但我无法使结果显示在MainWindow。我不知何故需要回到MainWindow并在打开文件后刷新结果。所以,基本上我需要做的是刷新已经打开的MainWindow(具有空的JFormattedTextFields)和适当的信息到JFormattedTextField

以下是MainWindow的代码:

package gui;

import java.awt.EventQueue;

import javax.swing.JFrame;

import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;

import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JSeparator;
import javax.swing.JComboBox;
import javax.swing.JTextPane;
import javax.swing.JFormattedTextField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.JCheckBox;
import javax.swing.text.NumberFormatter;

import datamodel.Taxpayer;

public class MainWindow extends JFrame{

    private JFrame frame;
    private Taxpayer taxpayer;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWindow window = new MainWindow();
                    window.frame.setVisible(true);                  
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MainWindow() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 590, 524);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Income Tax Calculator");

        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu menuFile = new JMenu("File");
        menuBar.add(menuFile);

        JMenuItem menuOpenFile = new JMenuItem("Open File");
        menuOpenFile.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                FileChooser chooser = new FileChooser();
                chooser.setVisible(true);       

            }
        });
        menuFile.add(menuOpenFile);

        JMenuItem menuExit = new JMenuItem("Exit");
        menuExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frame.dispose();
            }
        });
        menuFile.add(menuExit);

        JMenu menuOptions = new JMenu("Options");
        menuBar.add(menuOptions);

        JMenu menuTaxpayer = new JMenu("Taxpayer");
        menuOptions.add(menuTaxpayer);

        JMenuItem menuItemDeleteTaxpayer = new JMenuItem("Delete");
        menuItemDeleteTaxpayer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                TaxpayerDeletion deletedTaxpayer = new TaxpayerDeletion();
                deletedTaxpayer.setVisible(true);
            }
        });
        menuTaxpayer.add(menuItemDeleteTaxpayer);

        JMenu menuReceipt = new JMenu("Receipt");
        menuOptions.add(menuReceipt);

        JMenuItem menuItemAdd = new JMenuItem("Add");
        menuItemAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                ReceiptAdding receipt = new ReceiptAdding();
                receipt.setVisible(true);
            }
        });
        menuReceipt.add(menuItemAdd);

        JMenuItem menuItemDeleteReceipt = new JMenuItem("Delete");
        menuItemDeleteReceipt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                ReceiptDeletion deletedReceipt = new ReceiptDeletion();
                deletedReceipt.setVisible(true);
            }
        });
        menuReceipt.add(menuItemDeleteReceipt);

        JMenu menuHelp = new JMenu("Help");
        menuBar.add(menuHelp);

        JMenuItem menuItemHelp = new JMenuItem("Help");
        menuHelp.add(menuItemHelp);

        JMenuItem menuItemAbout = new JMenuItem("About");
        menuHelp.add(menuItemAbout);
        frame.getContentPane().setLayout(null);

        JLabel labelSelectTaxpayer = new JLabel("Please select a taxpayer from the list:");
        labelSelectTaxpayer.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelSelectTaxpayer.setBounds(25, 21, 211, 23);
        frame.getContentPane().add(labelSelectTaxpayer);

        JLabel labelPersonalDetails = new JLabel("Personal Details");
        labelPersonalDetails.setFont(new Font("Tahoma", Font.BOLD, 14));
        labelPersonalDetails.setBounds(238, 69, 211, 14);
        frame.getContentPane().add(labelPersonalDetails);

        JLabel labelName = new JLabel("Name:");
        labelName.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelName.setBounds(56, 105, 46, 14);
        frame.getContentPane().add(labelName);

        JLabel labelAfm = new JLabel("AFM:");
        labelAfm.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelAfm.setBounds(56, 130, 46, 14);
        frame.getContentPane().add(labelAfm);

        JLabel labelStatus = new JLabel("Status:");
        labelStatus.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelStatus.setBounds(56, 155, 46, 14);
        frame.getContentPane().add(labelStatus);

        JLabel labelIncome = new JLabel("Income:");
        labelIncome.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelIncome.setBounds(56, 180, 59, 14);
        frame.getContentPane().add(labelIncome);

        JLabel labelReceipts = new JLabel("Receipts:");
        labelReceipts.setFont(new Font("Tahoma", Font.PLAIN, 12));
        labelReceipts.setBounds(56, 205, 59, 23);
        frame.getContentPane().add(labelReceipts);

        JButton buttonCalculate = new JButton("Calculate");
        buttonCalculate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Report report = new Report();
                report.setVisible(true);
            }
        });
        buttonCalculate.setFont(new Font("Tahoma", Font.BOLD, 14));
        buttonCalculate.setBounds(429, 425, 135, 31);
        frame.getContentPane().add(buttonCalculate);

        JSeparator separatorLeftDetails = new JSeparator();
        separatorLeftDetails.setBounds(10, 81, 218, 2);
        frame.getContentPane().add(separatorLeftDetails);

        JSeparator separatorRightDetails = new JSeparator();
        separatorRightDetails.setBounds(346, 81, 219, 2);
        frame.getContentPane().add(separatorRightDetails);

        JComboBox comboBoxTaxpayerList = new JComboBox();
        comboBoxTaxpayerList.setBounds(246, 23, 319, 20);
        frame.getContentPane().add(comboBoxTaxpayerList);

        JComboBox comboBoxReceiptsList = new JComboBox();
        comboBoxReceiptsList.setBounds(143, 207, 357, 20);
        frame.getContentPane().add(comboBoxReceiptsList);


        JFormattedTextField formattedTextFieldAfm = new JFormattedTextField();
        formattedTextFieldAfm.setEditable(false);
        formattedTextFieldAfm.setEnabled(true);
        if(taxpayer != null){
            System.out.println("TAXPAYER NOT NULL");
            formattedTextFieldAfm.setText(String.valueOf(taxpayer.getTaxRegistrationNumber()));
            formattedTextFieldAfm.setVisible(true);
        }

        formattedTextFieldAfm.setBounds(143, 128, 357, 20);
        frame.getContentPane().add(formattedTextFieldAfm);

        JFormattedTextField formattedTextFieldStatus = new JFormattedTextField();
        formattedTextFieldStatus.setEditable(false);
        formattedTextFieldStatus.setEnabled(true);
        if(taxpayer != null){
            formattedTextFieldStatus.setText(taxpayer.getStatus());
        }

        formattedTextFieldStatus.setBounds(143, 153, 357, 20);
        frame.getContentPane().add(formattedTextFieldStatus);

        JFormattedTextField formattedTextFieldIncome = new JFormattedTextField();
        formattedTextFieldIncome.setEditable(false);
        formattedTextFieldIncome.setEnabled(true);
        //formattedTextFieldIncome.setText(String.valueOf(taxpayer.getIncome()));
        formattedTextFieldIncome.setBounds(143, 178, 357, 20);
        frame.getContentPane().add(formattedTextFieldIncome);

        JFormattedTextField formattedTextFieldName = new JFormattedTextField();
        formattedTextFieldName.setEditable(false);
        formattedTextFieldName.setEnabled(true);
        //formattedTextFieldName.setText(taxpayer.getName());
        formattedTextFieldName.setBounds(143, 103, 357, 20);
        frame.getContentPane().add(formattedTextFieldName);

        JSeparator separatorLeftCalculation = new JSeparator();
        separatorLeftCalculation.setBounds(10, 253, 218, 2);
        frame.getContentPane().add(separatorLeftCalculation);

        JLabel lblTaxCalculation = new JLabel("Tax Calculation");
        lblTaxCalculation.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblTaxCalculation.setBounds(233, 227, 200, 50);
        frame.getContentPane().add(lblTaxCalculation);

        JSeparator separatorReightCalculation = new JSeparator();
        separatorReightCalculation.setBounds(340, 253, 225, 2);
        frame.getContentPane().add(separatorReightCalculation);

        JLabel lblPleaseSelectOne = new JLabel("Please select one or more options for tax calculation");
        lblPleaseSelectOne.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblPleaseSelectOne.setBounds(155, 266, 505, 23);
        frame.getContentPane().add(lblPleaseSelectOne);

        JCheckBox checkBoxTotalTax = new JCheckBox("Total Tax");
        checkBoxTotalTax.setBounds(93, 306, 150, 23);
        frame.getContentPane().add(checkBoxTotalTax);

        JCheckBox chechBoxTaxAnalysis = new JCheckBox("Tax analysis(Basic tax, tax increase or decrease based on receipts)");
        chechBoxTaxAnalysis.setBounds(92, 332, 357, 23);
        frame.getContentPane().add(chechBoxTaxAnalysis);

        JCheckBox checkBoxReceiptsTotalValue = new JCheckBox("Total value of the gathered receipts");
        checkBoxReceiptsTotalValue.setBounds(93, 358, 271, 23);
        frame.getContentPane().add(checkBoxReceiptsTotalValue);

        JCheckBox checkBoxAmountDifferentCategories = new JCheckBox("Analysis of the amounts spent for different categories of expenditure");
        checkBoxAmountDifferentCategories.setBounds(93, 384, 421, 23);
        frame.getContentPane().add(checkBoxAmountDifferentCategories);


    }

    public void setTaxpayerInfo(Taxpayer taxpayer){
        this.taxpayer = taxpayer;
        System.out.println("Test message :Inside");
    }
}

这是FileChooser的代码:

package gui;


import input.TxtParser;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;








import datamodel.Taxpayer;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;

public class FileChooser extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private Taxpayer taxpayer;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FileChooser frame = new FileChooser();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public FileChooser() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 593, 436);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser();
        fileChooser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getActionCommand()!= null){
                    File file = fileChooser.getSelectedFile();
                    TxtParser txtParser = new TxtParser();

                        try {
                            taxpayer = txtParser.parse(file);
                            if(taxpayer == null){
                                System.out.println("NULL TAXPAYER");
                            }
                            System.out.println(taxpayer);
                        } catch (FileNotFoundException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }

                    MainWindow mainWindow = new MainWindow();
                    mainWindow.setTaxpayerInfo(taxpayer);
                    mainWindow.setEnabled(true);
                    mainWindow.setVisible(true);

                    close();
                }
            }
        });
        fileChooser.setBounds(0, 0, 582, 397);
        contentPane.add(fileChooser);
        this.setTitle("Income Tax Calculator");
    }



    private void close(){
        this.dispose();
    }
}

2 个答案:

答案 0 :(得分:2)

你有很多问题......

首先,您的MainWindow课程从JFrame延伸,但也创建另一个JFrame实例

public class MainWindow extends JFrame{

    private JFrame frame;

哪个帧实际上是包含内容或在屏幕上可见的帧?我首先删除extends JFrame

FileChooser类不是必需的,你复制的是JFileChooser类本身提供的功能,并通过这样做让你的生活更加艰难......

JMenuItem menuOpenFile = new JMenuItem("Open File");
menuOpenFile.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        switch (chooser.showOpenDialog(frame)) {
        case JFileChooser.APPROVE_OPTION:
            File file = fileChooser.getSelectedFile();
            TxtParser txtParser = new TxtParser();

            try {
            taxpayer = txtParser.parse(file);
            if (taxpayer == null) {
                System.out.println("NULL TAXPAYER");
            }
            System.out.println(taxpayer);
            setTextpayerInfo(taxPayer);
            } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            }
            break;
        }
    }
});

在现有的FileChooser课程中,您创建了另一个MainWindow的实例并致电setTextpayerInfo,但setTextpayerInfo没有做任何事情?!

您的setTextpayerInfo方法需要填写您希望用户能够操作的字段或控件。

将您的功能分成不同的类,以便您拥有一个TaxPayerPane,其中包含与TaxPayer类的管理直接相关的字段和控件。

然后将您需要的功能(菜单)和TaxPayerPane合并到JFrame的单个实例上。使用setter / getters根据需要在应用程序的各个部分之间传递信息。

这里的想法是分离和限制应用程序的不同部分,以便它们只执行它们所针对的单个作业。这解耦了您的代码,使其更易于管理和更改,并减少了尝试管理不同逻辑块的重叠复杂性

此外,避免null布局,他们更值得头疼。利用适当的布局管理器,将它们组合起来,不仅可以生成丰富的UI,还可以灵活地使用UI,以适应平台和外观之间的差异

答案 1 :(得分:1)

您尝试做的事情是以非常实用的编码形式进行的:模型 - 视图 - 控制器设计模式。 看一下wiki:http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

另一方面,如果你想要一个快速的方法来做到这一点,并且这不是最好的方法,你可以考虑将你的MainWindow传递给taxPayer类,在那里你可以将字段更改为全局变量并更改它们。

希望它对你有所帮助。