I need to listen to a Jbutton getting pressed however the implementation I have doesn’t seem correct. In the class that contains the JButton I have
public JButton button() {
return button;
}
In the class (call it, listenerClass) II listener to the button
buttonClass.button().addActionListener(new buttonActionListener());
public class buttonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//local method calls
}
}
I need to have the listener in listenerClass because that class contains the logic and methods I require. I feel its not correct to publish the whole JButton. I’m not sure how to just publish the buttons actionListener then I can do what ever I like in listenerClass. The buttonClass doesn’t know anything about the listenerClass
Thanks in advance 🙂
One way to achieve this is to add custom methods to the
buttonClassthat delegate to the button. For example you could add a method calledaddSomethingHappenedListenerthat will internally call `button.addActionListener’ and the caller does not need to know about the details.This way the caller does not even need to even know that it’s a button just that a certain event happened.