我试图在我的按钮“SaveImage”单击它时将其保存到给定的文件名中。当我尝试运行我的save(PrintWriter write)
into 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);
}
}
}
在你的类SaveButtonAction
中,你实现了actionPerformed
方法,因为这是在ActionListener
接口中定义的。
如果你检查源代码,你会发现ActionListener#actionPerformed
不会在它的签名中抛出任何类型的异常。然而,当你实现它时,你执行调用Oval#save
调用IOException
。尝试这样做时,在方法的签名中添加throws
子句,从而改变它。
这有效地破坏了界面定义的合同,并导致您的问题中提到的错误。
要么丢失throws
子句并在内部处理异常,要么如果你对它感兴趣,请将其包装在未经检查的异常中并重新抛出它。
我还强烈建议您阅读有关实现接口的正确方法。看来你在那方面缺乏。