Results 1 to 12 of 12

Thread: Multiple action listeners in one class

  1. #1
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts

    Multiple action listeners in one class

    Heh, i've been trying to get my head around it and did pretty much. But i'm not sure which is the best method. I realised when i was starting programming a GUI that programmers aren't going to create a class for every single action event. So, i devised a way to have multiple actions in one class so when you register the action there are multiple actions dependant on the parameter via one class. An example:

    Code:
    public class Listener implements ActionListener {
        
        public void actionPerformed(ActionEvent event) {
            String action = event.getActionCommand();
            
            if(action.compareTo("Create New Invoice") == 0) {
                // add and repaint content pane here
            }
        }
    And then carry on with multiple if else statements.

    Do you think this is a good method? I'd only create one instance of Listener (which is an ADT if you get confused by the class name) and then add it to every button. So i'd create the instance, doing Listener listen = new Listener(); and then button.addActionListener(listen("parameter")

    Would that work? Are there better methods?

  2. #2
    Large Member
    Join Date
    Apr 2004
    Posts
    3,720
    Thanks
    47
    Thanked
    99 times in 64 posts
    The usefulness or practability of such a class is entirely dependant on what you want it/your program to acheive. Presumably you are familiar with UML, go back to your class designs and real-world model and see what you need.
    To err is human. To really foul things up ... you need a computer.

  3. #3
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts
    It's not down to that, it's down to the fact that i'd have to write multiple classes extending the ActionListener to do different jobs, this would make things messy. I would write multiple methods which contain the actionPerformed() method but then that'd get messy too as for each button you'd have to register an event with a different method name whereas instead i can design a class which chooses an action dependant on the parameters.

    It's not to do with the design of the program, it's more to make things tidier and having less classes. I was just wondering if this idea has been adopted by other people or if there are other ideas on this? Alternative methods of approach perhaps?

  4. #4
    Large Member
    Join Date
    Apr 2004
    Posts
    3,720
    Thanks
    47
    Thanked
    99 times in 64 posts
    You could just use mutliple if..else in a single actionPerformed method using the EventObject getSource() method. But it's just a different solution, nothing special about any of them.
    To err is human. To really foul things up ... you need a computer.

  5. #5
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts
    That's basically what i'm doing now so yeh, same thing

  6. #6
    Senior Member
    Join Date
    Feb 2005
    Location
    Folsom, CA
    Posts
    221
    Thanks
    0
    Thanked
    0 times in 0 posts
    Code:
    private void setUILookandFeel(java.awt.event.ActionEvent evt)
        {
            String event = evt.getActionCommand();
            try
            {
                if (event.equals("Windows"))
                    UIManager.setLookAndFeel(windows_lnf);
                else if (event.equals("Metal"))
                    UIManager.setLookAndFeel(metal_lnf);
                else if (event.equals("Motif"))
                    UIManager.setLookAndFeel(motif_lnf);
                else if (event.equals("GTK"))
                    UIManager.setLookAndFeel(gtk_lnf);
                
                SwingUtilities.updateComponentTreeUI(this);
                //this.pack();  Commented out because it shrinks down the window
            }
            catch (ClassNotFoundException cnfe)
            {
                cnfe.printStackTrace(System.err);
            }
            catch (InstantiationException ie)
            {
                ie.printStackTrace(System.err);
            }
            catch (IllegalAccessException iae)
            {
                iae.printStackTrace(System.err);
            }
            catch (UnsupportedLookAndFeelException ulnf)
            {
                ulnf.printStackTrace(System.err);
            }
        }
        
        private void windowsMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                                
        {                                                    
    // TODO add your handling code here:
            setUILookandFeel(evt);
        }                                               
        
        
        private void gtkMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                            
        {                                                
    // TODO add your handling code here:
            setUILookandFeel(evt);
        }                                           
        
        
        private void metalMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                              
        {                                                  
    // TODO add your handling code here:
            setUILookandFeel(evt);
        }                                             
        
        private void motifMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                              
        {                                                  
    // TODO add your handling code here:
            setUILookandFeel(evt);
        }
    Sorry if the code is kind of complicated but that is the best example I had...what I am doing here is in my GUI there is a toolbar that allows the user of the program to customize the look and feel of the overall GUI to change it to whatever they are used to...the private actionperformed functions basically send the event object to the function setUILookandFeel analyze it there and deal with it...so that way I think you would avoid writing extra classes and so on...kinda similar to what you are doing but different...cause from what I understand you are writing a class and implementing a Listener...whereas my code does not.

  7. #7
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts
    Yeh i can see that. When you change the look and feel don't you have to repaint in order for the changes to take effect?

    I'm still learning how to use Swing and AWT though, i've literally scraped the surface

  8. #8
    Senior Member
    Join Date
    Feb 2005
    Location
    Folsom, CA
    Posts
    221
    Thanks
    0
    Thanked
    0 times in 0 posts
    No it automatically takes care of it. I think the UIManager class has internal dealings and it does it on its own. I could be wrong but the desired effect is working...so I guess it is taken care of.

  9. #9
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts
    Ah i see. Well not i've decided to nest my action listener class in the UI class, i had to do this because i needed it to have access to some of the methods but the problem was that i was instantiating the UI class which was a problem.

    Code:
    package oopj;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class UserInterface {
        
        private JFrame frame;
        
        /** Creates a new instance of createGUI */
        public UserInterface() {
            
            Listener listen = new Listener();
            JMenuBar menuBar = new JMenuBar();
            frame = new MainUI();
            frame.setLayout(new BorderLayout());
    
            JMenu fileMenu = new JMenu("File");
            JMenu toolsMenu = new JMenu("Tools");
            
            JMenuItem newInvoice = new JMenuItem("New Invoice");
            fileMenu.add(newInvoice);
            newInvoice.addActionListener(listen);
            
            JMenuItem saveInvoice = new JMenuItem("Save Invoice");
            fileMenu.add(saveInvoice);
            saveInvoice.addActionListener(listen);
            
            JMenuItem exit = new JMenuItem("Exit");
            fileMenu.add(exit);
            exit.addActionListener(listen);
            
            menuBar.add(fileMenu);
            
            frame.setJMenuBar(menuBar);
            welcomeScreen();
            frame.show();
        }
        
        /** This method creates a new invoice by updating the
         ** content pane and is called from the instantiated
         ** Listener class when an action is fired */
        public void createNewInvoice() {
            frame.invalidate();
            JPanel panel = new JPanel();
            panel.add(new JTextField(10));
            frame.add(panel);
            frame.validate();
            frame.repaint();
        }
        
        public void welcomeScreen() {
            JLabel label = new JLabel("Hello there!");
            JPanel welcomePanel = new JPanel();
            welcomePanel.add(label);
            frame.add(welcomePanel);
            frame.validate();
            frame.repaint();
        }
        
            /** this class is nested here because it needs to
             ** be visible to the UserInterface class so it can
             ** update the UI */
            public class Listener implements ActionListener {
        
                public void actionPerformed(ActionEvent event) {
                    String action = event.getActionCommand();
            
                    if(action.equals("New Invoice")) {
                        createNewInvoice();
                    }
                    else if(action.equals("Save Invoice")) {
                
                        System.out.println("Save Invoice plzthx!");
                    }
                    else if(action.equals("Exit")) {
                        System.exit(0);
                    }
                }
            }
    }
    That's what i have so far, it's nowhere near finished and is very rough. It doesn't work completely either, it JPanel doesn't repaint correctly when i click file > new yet the input box exists there.

  10. #10
    Senior Member
    Join Date
    Feb 2005
    Location
    Folsom, CA
    Posts
    221
    Thanks
    0
    Thanked
    0 times in 0 posts
    SO what is MainUI on line 14? Is that some other file that you have not told us about?

  11. #11
    Senior Member
    Join Date
    Feb 2005
    Location
    Folsom, CA
    Posts
    221
    Thanks
    0
    Thanked
    0 times in 0 posts
    I ran your program by changing MainUI to JFrame and adding a little main method at the bottom and it ran with the exception of the gui appearing all scrunched up in the beginning because there are no components in the beginning. I added a frame.pack() command in both your welcomeScreen function as the last line of that block of code and also another frame.pack() as the last line for newinvoice. That should sort things out a bit better.

  12. #12
    Senior Member Kezzer's Avatar
    Join Date
    Sep 2003
    Posts
    4,863
    Thanks
    12
    Thanked
    5 times in 5 posts
    Sorry guys, forgot the MainUI class.

    Code:
    package oopj;
    import javax.swing.*;
    import java.awt.*;
    
    public class MainUI extends JFrame {
        
        public MainUI() {
            super("Box Company");
            setTitle("Box company");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setPreferredSize(new Dimension(300,300));
            
            pack();
        }
    
    }
    It's a pointless class as i can make all the declarations in the UserInterface class. The reason why i was doing it was because i could make all the lookandfeel configurations to the class seperately so it's easier to change in the future

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. *sob* Action UT says goodbye
    By scottyman in forum Gaming
    Replies: 3
    Last Post: 14-01-2005, 10:56 AM
  2. The Action Movie
    By Private_mojo in forum Consumer Electronics
    Replies: 7
    Last Post: 14-07-2004, 04:53 PM
  3. If u vote ur a mupppet!
    By revol68 in forum Question Time
    Replies: 18
    Last Post: 02-02-2004, 03:11 PM
  4. Just how working class...
    By Stewart in forum General Discussion
    Replies: 17
    Last Post: 23-01-2004, 08:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •