如何解决 java.awt.event.ActionListener 不抛出 IOException 错误?

how to solve java.awt.event.ActionListener does not throw IOException error?

我正在尝试在单击我的按钮 "SaveImage " 时将我的数据保存到给定的文件名中。当我尝试 运行 我的 save(PrintWriter write) 进入 ActionListener 时它显示错误。

我的堆栈跟踪

actionPerformed (java.awt.event. ActionEvent) in
Oval.SaveButtonAction Cannot implement
actionPerformed(java.awt.event.ActionEvent) in
java.awt.event.ActionListener
overridden method does not throw java.io.IOException

这是我的代码。

public class Oval extends JPanel 
{


 private String filename = "";
    private PrintWriter writer;

public Oval() throws IOException
    {
        Buttons();      

    }

public void save(PrintWriter writer) throws IOException // this is my save method....
    {

        for(int i=0;i<ovalColor.size();i++)
        {
            writer.println(ovalX.get(i)+","+ovalY.get(i)+","+ovalColor.get(i).getRGB());
        }
    }

String filename  = "123.txt"
writer = new PrintWriter(filename);

/**
     * Action Listener for saveImage button
     */
class SaveButtonAction implements ActionListener  
    {
        public void actionPerformed(ActionEvent e) throws IOException // here i am getting Exception error
        {
            save(writer);
        }
    }
}

在您的 class SaveButtonAction 中,您实现 actionPerformed 方法,因为这是在 ActionListener 接口中定义的。

如果您检查源代码,您会发现 ActionListener#actionPerformed 不会在其签名中抛出任何类型的异常。然而,当您实现它时,您执行了对 Oval#save 的调用,该调用会抛出 IOException。尝试这样做时,您在方法的签名中添加了一个 throws 子句,从而改变了它。

这实际上破坏了接口定义的契约并导致您问题中提到的错误。

要么丢失 throws 子句并在内部处理异常,要么如果您对它如此感兴趣,则将其包装在未经检查的异常中并重新抛出。

我还强烈建议阅读有关实现接口的正确方法。看来你在这方面还欠缺