如何为Java Swing Button制作ActionListener

时间:2017-08-03 19:38:20

标签: java swing actionlistener

我想添加一个关闭BufferedWriter的ActionListener。总的来说,我的程序将变量值保存到文件中。这些值被读入在此Java GUI中运行的python脚本中。但是,我无法使(按钮单击)ActionListener工作。我只能得到一个WindowListener(用于帧关闭)。

对于WindowListener,我使用以下代码

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

        });

对于给出错误的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();
                }
            }
        });

我应该使用什么代码让侦听器识别按钮setVarFileBtn,然后关闭BufferedWriter?我是否缺少某些Java Swing代码概念,以便将BufferedWriter写入保存到文件中?

2 个答案:

答案 0 :(得分:1)

我解决了这个问题。我的错误发生是因为我有两个ActionListener用于同一个按钮。未示出的监听器用于写入变量值。一旦我将其添加到第一个监听器:

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

将变量值写入我的文件。

答案 1 :(得分:0)

要获取正在按下的按钮,您需要从事件中获取操作命令。你可以这样做:

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

"Save"JButton的名称。

相关问题