简体   繁体   中英

Java ActionListener in another Class

I am trying to build a small notepad application using the Java Swing library. I have a main function which calls a constructor of JFrame (NotepadClass) . In this NotepadClass I have a MenuDesigner class something like this:

this.setJMenuBar(new MenuDesigner());

The MenuDesigner class extends JMenuBar which calls actionListener ( MenuActionListener ) which is written in another class. Now my question is: If I click on "new" menuItem , the title which is in NotepadClass should change. How do I access a class that is two levels up?

Which concept of Java should I use to accomplish this?

Without seeing your code it's difficult to give a definitive answer, but one of the reasons to write a separate class to build your menu is that you can pass instances to the class.

this.setJMenuBar(new MenuDesigner(notepadClass));

This is one reason why it's good to have a model class or classes when you're building a GUI.

You can pass an instance of the highest level model class to all of your GUI components, and each component can get or set the parts of the model class that they represent.

You could pass down the NotepadClass in the constructors and provide a method to change the title.

Another option is to build the ActionListener inside the NotepadClass or let NotepadClass itself implement the Actionlistener interface so you can access the variables or methods.

Why is your actionListener for your menu in another class?

You could create a new class that implements ActionListener in which you can add you own logic. This way you can reuse it in another file.

Also, you should probably de-couple your MenuDesigner class by moving it into its own file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM