简体   繁体   English

如何为Java Swing Button制作ActionListener

[英]How to make ActionListener for Java Swing Button

I would like to add an ActionListener that closes the BufferedWriter. 我想添加一个ActionListener来关闭BufferedWriter。 Overall, my program is saving variable values to a file. 总的来说,我的程序将变量值保存到文件中。 These values get read into python scripts that are run in this Java GUI. 这些值被读取到在此Java GUI中运行的python脚本中。 However, I cannot get the (button click) ActionListener to work. 但是,我无法使(按钮单击)ActionListener工作。 I can only get a WindowListener (for frame closing) to work. 我只能让WindowListener(用于框架关闭)工作。

For a WindowListener I use the following code, 对于WindowListener,我使用以下代码,

frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    bufferFileWriter.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

        });

For an ActionListener, which gives error: java.io.ioexception stream closed, I use the following code: 对于给出错误的ActionListener:java.io.ioexception流关闭,我使用以下代码:

setVarFileBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Save the variable values when VarFileBtn pressed
                try {
                    bufferFileWriter.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        });

What code should I use to have a listener identify a button setVarFileBtn has been clicked, and subsequently close a BufferedWriter? 我应该使用什么代码来让侦听器识别已单击的setVarFileBtn按钮,然后关闭BufferedWriter? Am I missing certain Java Swing code concepts in order to make the BufferedWriter write's get saved to a file? 为了使BufferedWriter写操作保存到文件中,我是否缺少某些Java Swing代码概念?

I solved the problem. 我解决了问题。 My error occurred because I had two ActionListener's for the same button. 发生我的错误是因为我为同一按钮使用了两个ActionListener。 The listener not shown was for writing the variable values. 未显示的侦听器用于写入变量值。 Once I simply added this, to the first listener: 一旦我将其简单地添加到第一个监听器中:

try {
                    bufferFileWriter.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

the variable values were written to my file. 变量值已写入我的文件。

In order to get the button that is being pressed, you need to get the action command from the event. 为了获取被按下的按钮,您需要从事件中获取action命令。 You can do this like: 您可以这样做:

new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Save")) {
            // perform save code
        }
    }
}

"Save" is whatever the name of the JButton is. "Save"JButton的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM