Adding JButton to multiple toolbars


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Adding JButton to multiple toolbars

  1. #1
    Join Date
    Feb 2004
    Posts
    8

    Adding JButton to multiple toolbars

    I have created a button (Zoom) and an actionlistener for it.

    Is it possible to add the same button to a a JPanel (making a button bar) as well as to a JToolBar, so that both invoke the same listener?

    Cheers in advance

    Boro

  2. #2
    Join Date
    Feb 2004
    Posts
    11
    You would need to create a new JButton. How you handle the ActionListener, however, depends on if you used the anonymous inner class approach or if you created a custom action listener by implementing the ActionListener interface.

    If you created a custom ActionListener class, you simply add a single instance of that to both buttons:

    Code:
    MyActionListener listener = new MyActionListener();
    JButton zoom = new JButton("Zoom");
    JButton zoom2 = new JButton("Zoom");
    
    zoom.addActionListener(listener);
    zoom2.addActionListener(listener);
    If you used anonymous inner class approach, you'll need to create a method that both buttons call:

    Code:
    JButton zoom = new JButton("Zoom");
    JButton zoom2 = new JButton("Zoom");
    
    zoom.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            doZoom(event);
       }
    });
    
    zoom2.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            doZoom(event);
       }
    });
    Then the method called by both listeners

    Code:
    public void doZoom(ActionEvent event) {
        //code to zoom
    }

  3. #3
    Join Date
    Feb 2004
    Posts
    808
    making a separate, non-anonymous, proper button handler would be better
    The 6th edict:
    "A thing of reference thing can hold either a null thing or a thing to any thing whose thing is assignment compatible with the thing of the thing" - ArchAngel, www.dictionary.com et al.
    JAR tutorial GridBag tutorial Inherited Shapes Inheritance? String.split(); FTP?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center