I have a question and am not sure if this is the correct way of phrasing it and I can only hope you understand. I am working on a project using Swing. in this project I have a JFrame that is the main frame and it has a JButton. on clicking this button , a child frame pops up. Now if i clicked on the same JButton another frame still pops up and this can be continuous depending on how may clicks are made. My question here is how can I stop this from happening. My desired goal is that if I click on the JButton once only one frame should open and since this frame is open no other similar frames can be opened upon clicking on the JButton for the second time until the first child frame was or is closed.
The code tags only work if you have the code after [code=java] and before [/code]; I have corrected your code tags.
There is something wrong with your action listener.
If you use an anonymous class, which I think is a correct way to implement an action listener, then the source will be the same as the object you are adding it to. If you add an anonymous action listener to buttonX, then the source will always be buttonX. You can lost the bit about if (e.getSource() == buttonX), because that will always be true.
On the other hand, the source can never be buttonY. So any else if (e.getSource() == buttonY) bits will always be false, and that code will never be called.
Therefore, you can delete any code referring to another button, because it will never be called. Not in this listener. You will have to add different listeners to those other buttons.
You can also remove the if from any code referring to this button (buttonX), because that will always be called.
You also appear to have a try without a corresponding catch or finally. I can’t see why you have the try in the first place, but it won’t compile without a catch or finally. I think you might do well to remove the try.
Somebody else asked a similar question today. I shall say what I said then: why are you trying to open two frames. You ought usually to have one frame and one only. You might want dialogs, or internal frames, but probably not two frames. You can find out about them in the Java Tutorials.
Joined: Dec 15, 2010
I have now restructured my code and am now using the JInternalFrame as the child frame to the JFrame. but each time i click on buttonx another JInternalFrame opens. How do I stop this from happening?
In the buttons actionListener disable the button so it can't be clicked again.
Then add an InternalFrameListener to the internal frame you have created and in it's internalFrameClosed() method enable the button again.
This means when the button is pressed it will become disabled preventing further presses until the internal frame is closed when it will be re-enabled
subject: Stopping Duplicate Child JFrames Opening up upon clicking JButton Twice or more