DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 3 of 3
  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?

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links