Java event listeners

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()); // *** Let MainClass know what was clicked ?? } } 

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); } 
+4
source share
1 answer

One possible solution is MainClass implements ActionListener and pass its instance to MenuBar.createMenu ():

 public class MenuBar { public JMenuBar createMenu( ActionListener l ) { ... menuItem.addActionListener( l ); } ... } 

MainClass side:

 public class MainClass extends JFrame { @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); System.out.println( "Action triggered by: " + source ); } private static void createAndShowGUI() { ... frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MenuBar menuBar = new MenuBar(); JMenuBar mb = menuBar.createMenu( frame ); frame.setJMenuBar( mb ); ... } } 

Another way is to use java.beans.PropertyChangeListener and java.beans.PropertyChangeSupport

+3
source

Source: https://habr.com/ru/post/1480787/


All Articles