Reputation: 87
been trying to solve this problem for over a day now, and throwing in the white flag now. Taking this class at UMUC, and it's pretty much a self-study curriculum without any help so I really appreciate being able to ask this question here.
Just going to ask this question conceptually, because I can't even get my head wrapped around the concept.
I have a GUI class (subclass of JPanel) that creates a button. In the GUI class, the button uses ActionListener to recognize when it is clicked and performs validation tests on a textfield. So far so good!
Now, after the validation tests -- which ensure the input in textfield is numeric, I want to use this input to add to a variable in a different class (called Account).
In the third class, which includes main method -- I have created two instances of Account class: checking and saving, as well as Frame and adding GUI to the frame.
Problem: (1) How do I trigger the add method in account class when button in GUI class is clicked? (2) How do I ensure it applies to the specific instance of the Account class, i.e, either checking or saving?
Upvotes: 0
Views: 35
Reputation: 347194
There are a number of ways you might be able to do this. One would be to provide a ActionListener
property to your JPanel
, which you would then trigger once you've validated the input from the button. This a basic observer pattern (and you're already using it on the JButton
).
The problem is then how to get the information from the panel. You could provide getters on the panel, but this begins to tighten the coupling in your code.
A slightly better solution might be to provide your own listener/observer interface which you could then pass the information you want from the GUI to the listener, further de-coupling the API
I'd avoid passing the Account
to the GUI if possible, unless it has some reason to actually use/modify the account, it's best to keep it decoupled of the responsibility, the GUI's responsibility is to get and validate the information as best as possible and pass the processing on to the observer/listener.
In this case, you just need to wrap the listener/observer around a particular instance of the account, so when it's triggered, it's operating on the correct account
Upvotes: 1