using actionPerformed fails because a method in it can throw exceptions
SOLVED! Thanks all for quick answers, the problem was that i thought that if u catch an exception that u still have to add throws Exception to the header ^^ pretty dumb off me, thanks again! ------------------------------------ORIGINAL POST------- Hello, I have a method load(), this method throws IOException's. I'm trying to make this:
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Load")){
load();
}
}
the problem is, I should add throws IOException to the actionPerformed, but if I do so. I get an error saying: "The class isnt declared abstract or doesn't overri开发者_StackOverflowde public void actioPerformed()
So you need to work out what you want to happen if load
throws an IOException
. The method calling actionPerformed
isn't expecting an IOException
, so it can't possibly handle it.
Can you handle it, e.g. by displaying an error message and letting the user try again? If so, put a try/catch
block in actionPerformed
and handle it that way.
If you can't, you could catch the exception and wrap it in a RuntimeException
. That's generally a fairly harsh way of dealing with the exception, but in some cases it's the best approach. Swing will catch the exception and log it, so in this case it may not be much help... but you may be able to change that default behaviour too.
Is there a reason you can't simply surround the call to load()
with a try
-catch
block? For example:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Load")) {
try {
load();
} catch(IOException e) {
// Handle the error here
}
}
}
This assumes that you have some behavior you can execute if load()
fails. What does load()
do? What should your application do if it can't load?
You either need to throw the IOException, or surround the method that does (presumably getActionCommand()?) with a try/catch.
You have to think of how to handle the IOException
within the context of actionPerformed()
.
One approach would be to use a try/catch block, and in the catch display a dialog that tells the user that something went wrong. Better if you can translate the exception into something meaningful, and best if you can give the user some way to recover from the problem.
Incidentally, if you're doing some long-running IO operation, you shouldn't be doing it on the event dispatch thread -- it will cause delays in your GUI. And rather than sharing one ActionListener
between multiple actions (with the if condition to see which action you've been called by), create a subclass of AbstractAction
for each.
精彩评论