Java Reference
In-Depth Information
The upside of this approach is that it allows the class you already have as a container to act as a
listener for its child components. The downside is that you need to add some extra code when you
want to add a listener to multiple buttons, for instance, and need to know which button (not just
that a button) was clicked. More about how to deal with this later.
Finally, you can also decide to keep the listener separated as much as possible by defining it in a new class:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ActionListenerExample extends JFrame {
public ActionListenerExample() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Click Me!");
MySimpleButtonListener listener = new MySimpleButtonListener();
btn.addActionListener(listener);
this.add(btn);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ActionListenerExample();
}
});
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MySimpleButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(
null,
"You clicked me, nice!",
"Aw yeah!",
JOptionPane.PLAIN_MESSAGE);
}
}
Search WWH ::




Custom Search