JMenuItem ActionListener help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Stubert
    New Member
    • Dec 2007
    • 20

    JMenuItem ActionListener help

    Hi there just a quick question, if I have multiple JMenuItems do I need to create an inner class ActionListener for each and every JMenuItem I create? Or is there a more efficient way of doing it?

    I know I could just use event.getSource and check it all in one big ActionListener, but I've been informed that this is bad pracitce and should be done using inner classes.

    Just wondering if there were any other ways of achieving this?

    Thanks,

    Stuart
  • sukatoa
    Contributor
    • Nov 2007
    • 539

    #2
    do I need to create an inner class ActionListener for each and every JMenuItem I create?
    Yep... you can..... and it is a good practice... but it consumes more lines of code.....

    See the Sun's Java tutorials for more details about it.....

    regards,
    sukatoa

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by Stubert
      Hi there just a quick question, if I have multiple JMenuItems do I need to create an inner class ActionListener for each and every JMenuItem I create? Or is there a more efficient way of doing it?

      I know I could just use event.getSource and check it all in one big ActionListener, but I've been informed that this is bad pracitce and should be done using inner classes.

      Just wondering if there were any other ways of achieving this?

      Thanks,

      Stuart
      Or, alternatively create an Action object for a JMenuItem. It fully populates and
      decorates a JMenuItem and handles whatever needs to be done when the JMenuItem
      is pressed.

      Going the getSource() route ends up in a silly sequence of if-statements and you'll
      end up with much more code at the end. Better create a little class for your item:
      one class per item; it's easier to maintain than just one big method with a bunch
      of if-statements in it. The little Action classes don't even need to be inner classes.

      kind regards,

      Jos

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        ... also ask aunt Google about the Command pattern.

        Comment

        • Stubert
          New Member
          • Dec 2007
          • 20

          #5
          Thanks for the replies, at first I was using a stupid amount of if statements in one actionPerformed method and it was just too messy to understand, hence the first post. I'm going to look up the Command pattern now and I'll get back to you guys.

          Thanks again,

          Stuart

          Comment

          Working...