event
Change Event behavior dynamically
In this example we are going to see how to change the behavior of an event dynamically in your Java program.
It is very simple to add this kind of functionality in your application. All you have to do is:
- Create some classes that implement the
ActionListener
interface. - Bundle these
ActionListener
with a specific button or component usingaddActionListener
method. - According to your need you can dynamically remove an
ActionListener
usingremoveActionListener
and thus change the behavior of a specific event.
Let’s take a closer look at the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class DynamicEvents extends JApplet { private java.util.List list = new ArrayList(); private int i = 0; private JButton button1 = new JButton("A"); private JButton button2 = new JButton("B"); private JTextArea textArea = new JTextArea(); class B implements ActionListener { @Override public void actionPerformed(ActionEvent event) { textArea.append("Button was pressedn"); } } class EventCounter implements ActionListener { private int index; public EventCounter(int indx) { index = indx; } @Override public void actionPerformed(ActionEvent event) { textArea.append("Counted Listener " + index + "n"); } } class B1 implements ActionListener { @Override public void actionPerformed(ActionEvent event) { textArea.append("A pressedn"); ActionListener actListener = new EventCounter(i++); list.add(actListener); button2.addActionListener(actListener); } } class B2 implements ActionListener { @Override public void actionPerformed(ActionEvent event) { textArea.append("B pressedn"); int end = list.size() - 1; if (end >= 0) { button2.removeActionListener((ActionListener) list.get(end)); list.remove(end); } } } @Override public void init() { Container container = getContentPane(); button1.addActionListener(new B()); button1.addActionListener(new B1()); button2.addActionListener(new B()); button2.addActionListener(new B2()); JPanel jPanel = new JPanel(); jPanel.add(button1); jPanel.add(button2); container.add(BorderLayout.NORTH, jPanel); container.add(new JScrollPane(textArea)); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { showUI(new DynamicEvents(),800,600); } }); } public static void showUI(JApplet app, int w, int h) { JFrame jFrame = new JFrame(); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.getContentPane().add(app); jFrame.setSize(w, h); app.init(); app.start(); jFrame.setVisible(true); } }
This was an example on how to Change Event behavior dynamically.