有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java WindowEvent。窗口关闭会提前终止程序

我正在尝试使用GUI将数据写入文本文件。我在执行此操作时遇到了一个问题,并且能够确定WindowEvent出于某种原因提前终止了程序

最初,我在WindowEvent行后面有outFile.close();,所以JTextArea中的文本不会被传输到文本文件中。在切换了几行代码之后,我意识到,当尝试使用WindowEvent自动关闭JFrame时,之后没有任何代码被执行

我如何解决这个问题

import ...

public class TxtManager {
    static Input input;

    public static void overwriteCurrentFile() throws IOException {
        TxtManager txt = new TxtManager();
        input = new Input(txt);
    }

    public synchronized void sendData() throws IOException {
        try {
            BufferedWriter outFile = new BufferedWriter(new FileWriter(file1));
            String data = input.textArea.getText();
            outFile.write(data);
            outFile.close();
            input.frame.dispatchEvent(new WindowEvent(input.frame,WindowEvent.WINDOW_CLOSING));
            // Code from this point on in the try block does not execute.
            System.out.println("Finished with the write out..."); // Used for pinpointing the problem
            JOptionPane.showMessageDialog(null,"Data in " + TxtManager.file1 + " has been overwritten successfully.");
            TxtManager.showData = true;
            TxtManager.menu2();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,"Error: " + ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        }
    }
}

class Input extends Thread {
    TxtManager txt;
    public JTextArea textArea;
    public JFrame frame;
    private JButton button;

    public Input(TxtManager txt) throws IOException {
        this.txt = txt;
        JOptionPane.showMessageDialog(null,"Enter desired data into the GUI screen.\n" +
            "Press the <Done> button once you are finished.");
        frame = new JFrame("Prompt");
        JPanel panel = new JPanel(new BorderLayout());
        frame.add(panel);
        JLabel label = new JLabel("Enter desired data.");
        panel.add(label,BorderLayout.NORTH);
        textArea = new JTextArea(15,80);
        panel.add(textArea,BorderLayout.CENTER);
        panel.add(new JScrollPane(textArea));
        button = new JButton("Done");
        panel.add(button,BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        start();
    }

    public void run() {
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    txt.sendData();
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null,"Error: " + ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
}

共 (0) 个答案