Reputation: 25
I'm creating a "GUI" application, with aim to make a code clear and by separating those "GUI" components into classes (you'll see below what I mean), which for now goes well with menu bar, but I'm wonder now, since I want to implement ActionListener to them, where it is best to do it in which class, for example in this case of menu bar class, in his class or to implement action listener in Main and than implement abstract method which will use methods we want to perform action?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public final class Main extends JFrame {
private MenuBar menuBar;
public Main() {
setTitle("GUI");
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initGUI();
}
public void initGUI() {
menuBar = new MenuBar(this);
// this is last update before I started posting this, I decided to
// access exitMenu variable and than to addActionListener to it from a here, which is currently not working
menuBar.exitMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new Main();
}
}
Menu bar class:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public final class MenuBar {
public JMenu newMenu;
public JMenu aboutMeMenu;
public JMenu exitMenu;
public MenuBar(JFrame jFrame) {
JMenuBar menubar = new JMenuBar();
initNew(menubar);
initAboutMe(menubar);
initExit(menubar);
jFrame.setJMenuBar(menubar);
}
public void initNew(JMenuBar menubar) {
newMenu = new JMenu("New");
menubar.add(newMenu);
}
public void initAboutMe(JMenuBar menubar) {
aboutMeMenu = new JMenu("About Me");
menubar.add(aboutMeMenu);
}
public void initExit(JMenuBar menubar) {
exitMenu = new JMenu("Exit");
menubar.add(exitMenu);
}
}
Upvotes: 0
Views: 88
Reputation: 15729
One standard approach is to have your Main class, or some class fairly "close" to Main, handle all or most of the actions. There will typically be a giant switch statement based upon action.getActionCommand()
that passes control to the appropriate function. I for one do not like this approach, but it does have the advantage that it's fairly simple to follow.
IMO the far superior approach is to create AbstractActions
and hook up to them. They can be organized in whatever way makes sense for your application. What's nice is that they are nicely encapsulated, feel much more "OO-like", etc.... Also, multiple GUI elements can share an action. e.g. both a button and a menu can invoke the "SaveFileAction" action. And actions can be centrally enabled and disabled. If there is no file to save, that "SaveFileAction" can be fairly easily disabled.
Upvotes: 3