I am extremely confused as to how a JButton works. I have read over the oracle documents of the JButton, but I have failed to see how a JButton can have an actionlistener added to it. I have really always wondered how things like JFrames and all that can have things like .addMouseListener and all that. Can anyone explain how a JButton can have an actionListener added to it like the .addActionListener(...) syntax?
My reason for wanting to know how to do this is to create my own “JButton” per say which can have an actionListener added to it and it will fire events when needed. Is this even possible or no?
Here is what you have to do to understand the architecture. First the Design pattern used here is the Observer Pattern –
You can find more information about implementing it at here.
But if your objective is to make your own JButton the best approach is to Subclass JButton.
You asked about how
JFramecan haveaddMouseListener– It’s becauseJFrameextendsjava.awt.Component. Hope this helps.EDIT
Observer doesn’t do anything. Subject notify the Observers if anything change. This is the notify method.
Back again to the Packet and the Bucket example –
Packet – Observer
Bucket – Subject
Bucket wires the Packet that a new Packet has entered the Bucket. In classes Bucket class will call the notify method and all the registered Packets will be notified. If a Packet wishes to unsubscribe itself from the Bucket it just needs to call the Unsubscribe method and it will remove the Object from the ArrayList of the Bucket.