I am writing a simple application in java. When creating the menu, the question arose:

For each menu item you need to create an action handler. I read an example from Horstmann. And the question arose - for each action to write a separate class-successor from AbstractAction or you can do something like this:

fileMenu.add(new AbstractAction("Exit") { public void actionPerformed(ActionEvent event) { System.exit(0); } }); 

How correct?

    4 answers 4

    If your code processing is reduced to a few lines, then creating a separate class is not necessarily anonymous. if you do not like this option (or does not fit), use listeners:

     class AbcFrame extends JFrame implements ActionListener { public AbcFrame() { new JMenuItem("Help").addActionListener ( this ); new JMenuItem("About").addActionListener ( this ); } public void actionPerformed(ActionEvent event) { // по event.getSource() определяем кто сгенерировал ивент // и обрабатываем } } 

    ps imkho it is more convenient 1st option since the processing of a specific action is in a separate method and does not interfere with the readability of the code

      I also deal with it now, it seems you can not create separate classes,
      and do as you wrote, judging by the examples

      • Well, sort of, you can <a rel="nofollow" href=" download.oracle.com/javase/tutorial/uiswing/misc/…> have <a rel = "nofollow" href = " download.oracle.com/javase/tutorial / uiswing / examples / misc / ... > where for each action a separate class is conscientiously created. So, it's interesting how to do it better) - Pavel
      • one
        Yes, exactly, apparently and so it is possible, but the creation of separate classes looks more convenient and readable, and probably it would be more correct. - Kobayashi_Maru
      • one
        I thought so too. And I am writing a new class for each action - in the end it’s more efficient, though a bit more code. - Pavel

      Horstmann describes event handlers using nested anonymous classes (it is in your example above). Therefore, you can either use anonymous nested classes for each event handler, or make one and inherit from it. I advise you to carefully read again how Horstmann's event handler is implemented (Volume 1).

        It is not necessary to do a class for every action. You can do this for example:

         JMenuItem b=new JMenuItem(xx[0]); b.setName(xx[1]); b.addActionListener(this); m.add(b); 

        and public void actionPerformed (ActionEvent ae) to process by name