在java中,我可以在构造对象后更改对侦听器的引用吗?例如,当实例化此类的对象时,我可以使用其设置器更改侦听器吗?如果我不能,我该怎么做,我的意思是在需要时更改侦听器?
public class ListenerTest extends JFrame {
ActionListener listener;
public ListenerTest() {
JPanel jPanel = new JPanel();
JButton jButton = new JButton("Activate!");
jButton.addActionListener(listener);
jPanel.add(jButton);
add(jPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Demo Drawing");
setLocationRelativeTo(null);
pack();
setVisible(true);
}
public ActionListener getListener() {
return listener;
}
public void setListener(ActionListener listener) {
this.listener = listener;
}
public static void main(String[] args) {
ListenerTest frame = new ListenerTest();
}
}