You're going to need to pass some kind of reference of some kind of object to your EventHandler
, what you don't want to do is give more power to the EventHandler
then it should have, for example, your add flower event handler should only be capable of doing that and not, for example, setting fire to the world (or removing everything from the component).
The event handler doesn't need to know anything about HOW things happen, only that when it calls some method, it does.
Start by creating a couple of interfaces, for example...
public interface Flower {
// What ever properties you want you flower to have
}
public interface Ground {
public void add(Flower flower);
// Other stuff you might like ground to have/do
}
These describe the contract to other users of these interfaces, describing what can be done or obtained from them. This is a very important concept in OO programming.
You then need to provide some kind of implementation for these classes
public class AFlower extends ... implements Flower {
}
public class SomeGround extends ... implements Ground {
}
These are the physical implementations of these interfaces, you could have any number of implementations of Flower
, Rose
, VenusFlyTrap
, but Ground
won't care...
Now, in order for your EventHandler
to be able to actually do anything useful, you will need to pass it an instance of Ground
to work with, for example...
public class Eventhandler implements java.awt.event.ActionListener {
private Ground ground;
public Eventhandler(Ground ground) {
this.ground = ground;
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Flower flower = new AFlower();
ground.add(flow);
}
Then when you create an instance of EventHandler
, you would pass it an instance of Ground
, for example...
example1.Ground g = new SomeGround();
// ground object
javax.swing.JFrame window = new javax.swing.JFrame("windowwithbutton");
//window (JFRAME)
javax.swing.JPanel panel = new javax.swing.JPanel();
//content (JPANEL)
javax.swing.JButton ab = new javax.swing.JButton("add");
ab.addActionListener(new EventHandler(g));