I am trying to split the components of my Java application into different classes. For example, I have a MenuBar class called from MainClass that creates a JMenuBar.
Usually I have to use an ActionListener in the MenuBar class and override actionPerformed () so that everything is organized. But if I do, how can I tell MainClass what was clicked?
I tried to implement my own ActionListener, but could not find a solution capable of sending events to other classes.
MainClass.java
public class MainClass extends JFrame { private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(false); JFrame frame = new JFrame("Main Window"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MenuBar menuBar = new MenuBar(); JMenuBar mb = menuBar.createMenu(); frame.setJMenuBar(mb); frame.setSize(400,400); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
MenuBar.java
public class MenuBar implements ActionListener { public JMenuBar createMenu() { JMenu menu; JMenuItem item; JMenuBar menuBar = new JMenuBar(); menu = new JMenu("Main"); menuBar.add(menu); item = new JMenuItem("New"); menu.add(item); return menuBar; } @Override public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e.getSource()); System.out.println("Action triggered on: "+source.getText());
EDIT
I realized that I can just create an ActionListener in MainClass and pass this to the MenuBar class, for example:
Modified MainClass.java
ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println(ae.getActionCommand()); } }; MenuBar menuBar = new MenuBar(); frame.setJMenuBar(menuBar.createMenu(l));
And then, in the MenuBar, I just apply an ActionListener to each of the menu items.
Changed MenuBar.java
public JMenuBar createMenu(ActionListener l) { item = new JMenuItem("Hide When Minimized"); item.addActionListener(l); menu.add(item); }
Marc source share