I am having a problem with a JButton that needs to be clicked twice. Exactly when is the listener for a button invoked? I am guessing that my problem is because the button only gets focus the first time it is clicked and then executes the listener on the second click. If I tab to the button, at which time it has focus, it then works on the first click. Is something required somewhere in the button definition that says to get focus and execute the listener on the same click? Or do I need to look elsewhere because a single click should be getting focus and executing the listener (which makes more logical sense to me)? TIA.
Once again the problem is your code and we can't help without a SSCCE.
Run the demos from the Swing tutorial for working examples. I'm sure you have been given a link to the tutorial in past questions. If not then read the JButton API and you will find a link.
Dennis Putnam wrote:. . . . Exactly when is the listener for a button invoked? I am guessing that my problem is because the button only gets focus the first time it is clicked and then executes the listener on the second click. . . . .
Don't know. It might even be platform‑dependent. I suggest you add a line to your Listener which prints the click count from the button. There is an example in the Java™ Tutorials. Also try a focus listener on the button to see when it gains focus.
I take it from your reply that you do not know (without code) if a button is supposed to get focus and execute a listener on a single click. That implies (albiet illogically to me) that whether or not the listener is executed is inconsistent and based on code as it relates to focus.
No, I know what should happen and I answered your queston. I stated the problem was with your code and we can't provide a solution without a SSCCE.
I take you haven't read the Swing tutorial and downloaded the code and tested it to see what happens?
The tutorials write code properly so you can easily determine the proper behaviour by running the demo code.
And once again nobody really knows what you are taking about. One is suggestion is referring to an ActionListener, another is referring to MouseLister (which should NOT be used).
I'm using an ActionListener. I'll look into MouseListener again which I thought was like cracking an egg with a sledghammer for just listening for a click. Thanks.
Dennis Putnam wrote:. . . . I'll look into MouseListener again . . . .
Rob Camick is right; don't use a mouse listener. Not because it is too much like a sledgehammer to crack an egg but more that it is like using a toffee hammer to crack the road surface. It lack the specificity an action listener would have.
We don't have time for this. We've gotta save the moon! Or check this out: