Hi curt22 ,
It's best practice to separate event handling method from the event source class(class which contains UI widgets). So that later it will be easy to change that without affecting event source class.
Consider this example :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingMenu {
// Inner Class Implementation
/*
class actionListener implements ActionListener {
public void actionPerformed(ActionEvent avt) {
System.out.println("Triggered");
}
} */
public static void main(String[] args) {
SwingMenu swingMenu = new SwingMenu();
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem demo = new JMenuItem("demo");
//demo.addActionListener(swingMenu.new actionListener()); // Using Inner class Implementation
demo.addActionListener(new actionListener()); // Using a Separate class
file.add(demo);
menuBar.add(file);
JFrame frame = new JFrame("Frame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.NORTH,menuBar);
frame.setSize(300,400);
}
}
// Event Handling class
class actionListener implements ActionListener {
public void actionPerformed(ActionEvent avt) {
System.out.println("Triggered");
}
}
In this example I have written a separate class for event handling. you can use inner class or a separate class
Hope this helps
Reputation Points: 10
Solved Threads: 6
Junior Poster in Training
Offline 80 posts
since Sep 2006