Best Practice: Where to put Listeners?

In a Swing application the typical way of handling events is to add a listener. So far, so good.
But where to locate the listeners? Obviously there are a lot of possible solutions:
- Scatter them all over your code, like using anonymous listeners.
- Implement all of them in a single, explicit class.
- Only uses windows as listeners.
- etc.
The intention of my question is not to get a rather long list of more ideas, or to get pros or cons of any of the above suggestion. My actual question is: Is there a best practice for where to locate a listener's implementation? I mean, after decades of Swing and thousands of Swing based applications, I am sure that there must be a best practice where to but listeners implementations.

mkarg wrote:
In a Swing application the typical way of handling events is to add a listener. So far, so good.
But where to locate the listeners? Obviously there are a lot of possible solutions:
- Scatter them all over your code, like using anonymous listeners.
- Implement all of them in a single, explicit class.
- Only uses windows as listeners.
- etc.
The intention of my question is not to get a rather long list of more ideas, or to get pros or cons of any of the above suggestion. My actual question is: Is there a best practice for where to locate a listener's implementation? I mean, after decades of Swing and thousands of Swing based applications, I am sure that there must be a best practice where to but listeners implementations.You've asked other similar questions about best practices. No matter how long Swing has been around, people still program in a variety of ways, and there are lots of areas where there are several equally correct ways of doing things. Each way has its pros and cons, and the specific situation drives towards one way or the other. One's best practice of using anonymous listeners will be another's code smell. One's best practice of using inner class will be another's hassle.
So you will probably only get opinions, and likely not universally recognized best practices.
That being said, here is my opinion (nothingmore than that, but it has a high value to me :o) :
In yous list of options, one thing that is more likely to form a consensus against it, is "only uses window as listeners". I assume you mean each frame is implemented as a MyCustomFrame extends JFrame , and add this as listener on all contained widgets.
This option is disregarded because
1) extending JFrame is generally not a meaningful use of inheritance (that point is open to debate, as it is quite handy)
2) register the same object to serve as a listener for several widgets makes the implementation of listener callbacks awkward (lots of if-then-else). See [that thread|http://forums.sun.com/thread.jspa?forumID=57&threadID=5395604] for more arguments.
Now, no matter what style of listeners you choose, your listeners shouldn't do too much work (how much is too much is also open to debate...):
if a listener gets complicated, you should simplify it by making it a simple relay, that transform low-level graphical events into functional events to be processed by a higher-level class (+Controller+). I find the Mediator pattern to be a best practice for "more-than-3-widgets" interactions. As the interactions usually involves also calls to the application model, the mediator becomes a controller.
With that in mind, sort anonymous listeners are fine: the heavy work will be performed by the mediator or controller, and that latter is where maintenance will occur. So "Scatter them all over your code" (sounds quite pejorative) is not much of an issue: you have to hook the widget to the behavior somewhere anyway, the shorter, the best.
For simpler behavior, see the previous reply which gives perfect advice.

Similar Messages

  • Best practices for adding CLICK listeners to complicated menus?

    OK, I’m gonna wear out my welcome but here’s my last question of the day:
    I’ve got a project that is essentially a large collection of menus, some buttons common across multiple screens, others unique. The following link is the work in progress, most of the complexity is in the “Star Action Items and Forms” area (btw: the audio in the launch presentation is just a placeholder track, I know we can't use it):
    http://www.appliedcd.com/Be-A-star/Be-A-star.html
    To deal with the large number buttons my timeline simply has the following for every menu frame:
    stop();
    initFrame();
    The initFrame() function then has a list of frames and activates the buttons appearing on each screen, a very simplified example follows. In this example commonButtons span all 3 menus, semiCommonButtons span menu 2 and 3, button1A, button2A, etc… are unique per menu.:
    function initFrame():void {
         var myFrame:String = this.currentLabel;
         commonButton1.addEventListener(MouseEvent.CLICK,onInternalLink);
         commonButton2.addEventListener(MouseEvent.CLICK,onInternalLink);
         commonButton3.addEventListener(MouseEvent.CLICK,onInternalLink);
         switch(myFrame) {
              case "menu1":
                   button1A.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button1B.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button1C.addEventListener(MouseEvent.CLICK,onInternalLink);
              break;
              case "menu2":
                   semiCommonButton1.addEventListener(MouseEvent.CLICK,onInternalLink);
                   semiCommonButton2.addEventListener(MouseEvent.CLICK,onInternalLink);
                   semiCommonButton3.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button2A.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button2B.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button2C.addEventListener(MouseEvent.CLICK,onInternalLink);
              break;
              case "menu3":
                   button3A.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button3B.addEventListener(MouseEvent.CLICK,onInternalLink);
                   button3C.addEventListener(MouseEvent.CLICK,onInternalLink);
              break;
    The way the project was designed, I “thought” menu3 would only be accessible through menu2, thus guaranteeing that the semiCommonButtons would get initialized, but I forgot the functionality of my back button could jump the user directly from menu1 to menu3. The solution is simple, initialize every button on every navigation  target, however, is this really the best way to initialize a bunch of buttons? Another possible approach would be to have an array of button instance names and a function that said: if instance XYZ exists, add listener, then simply loop through the array on every nav target. Anyone with more experience have advice on best practices in this situation?

    Hmmmm just run a test on this whereby I added the above snippet to my master page. I then publish a major version. I can see that every (Welcome) custom page layout has this data widget working, providing I add the div to the page..  
    I wonder if the reason I can't add the snippet  directly  to an individual custom layout page is a bug or am I doing something incorrectly?
    Daniel

  • Best Practice - When to put things on a different layer?

    I'm designing a simple website that includes a FLVPlayer
    component, some ComoBox components that control the player, and
    some text. Is there a technical reason why the player, the
    comboboxes and the text should each be on different layers, or is
    it more a matter of housekeeping? Is there a rule of thumb that
    indicates when a new layer should be used for something?
    Thanks

    I use them for organization, most of the time. When tweening
    symbols on the stage there can only be one symbol on the layer or
    it will not work. There should be a layer specifically for
    actionscript as well.

  • Where to put Validation Code?

    Up until now, Im still having second-thoughts of where to put validation code when setting attributes of an entity.
    Right now I have created lots of custom validators --(implement JbovalidatorInterface) that calls stored procedures to validate the value entered. But sometimes, i just use a ViewObject and query it on the setterAttribute method of the Entity and just manually throw a JboException of the value is invalid based on some business rule.
    Question is, what are the best practices where to put validation codes? do we have to be strict that we always put all validations on Validators or are we free to just throw JboExceptions anywhere on the BC classes' code.
    regards,
    Anton

    1. The reason I have a custom validator and I don't normally use the built in declarative validators is that the error message generated when the validation fails is fixed, only one message. I decided to have create a custom validator is that I need to test a one attribute for many cases in each case should produce a distinct error message. So if I use the built in validators, I would have to create lots of built in validators for that single attribute only. (and i have lots of entities and lots of attributes that needs business rule validation). So, I decided to create a custom validator, that calls the stored procedure, the stored procedure takes care of all test cases, for that attribute only, and I can return a dynamic error message depending on the test case that failed. What do you think about the approach?
    It's a little extra work to create a reusable validator class that will only be used once, but whether you do it that way or encapsulate the call in a helper class that your one-off method validator code delegates too, it seems similar to me. So it's more of a stylistic choice for you which you like better. Now, if your reusable validator were enable to encapsulate
    2. When I said anywhere; I meant inside the setterAttribute methods on the Entity and on the ViewRowImpl, orThe ViewImpl class or inside a method on an ApplicationModule?
    Rather than writing code in the setAttribute, I recommend using attribute-level method validators. This makes it more clear where all your validation code lives.
    I don't recommend performing validation in the view object level since entity objects are the component in the system that are tasked with handling validation. It would be easy to circumvent view level validation checks unless you make a lot of assumptions about exactly how your application is working.
    3. One other issue is that Validator methods are for validation purposes only. So its not a good idea to put in attribute setters to other attributes inside there. So you put the attribute setter logic outside of the validator usually inside the setAttribute() just after validator returns. But there are cases that is very straightfoward to put validation logic inside the setAttribute; meaning, inside the setAttribute() method, I test for a condition, if it fails, just throw a JboException, if its true, continue with the otherAttributes setter logic.
    Whether attribute setting of other attributes is performed in a setter method or in an attribute-level method validator, either way you will need conditional logic to avoid going into a validation "loop" (which eventually will throw an exception if after 10 attempts the object is still not valid at posting time.

  • Where to put the patches ????

    Hi All,
    I have a question about where to keep the patches on weblogic6.1+sp2.
    what is the best practice/way to put the patches on wls6.1/wls8.1 .....iam more or less interested on putting these patches on wls6.1+sp2
    say for some reason, i need 4 patches(which are related to the same problem) ....and i downloaded it from support.bea.com site ...and then ......what is the best practice to place them....where ??
    We have been keeping the 4 patches(or all of them) at CLASSPATH level....but i don't know if it could be a issue for HOT DEPLOYMENT or not ....OR some other issues ?
    please let me know what is the BEST practice and other practices of keeping these patches ????
    thanks alot.
    -sangita

    I put patches on the knees of my denim overalls. I also like to wear a straw hat and carry around a pitchfork. It makes me look like a hick, but people better respect me or I will spear them with my pitchfork!

  • Oim11g - Best Practice for Logging

    Hello all,
    want to know  the best practice or common usage of error logging in oim11g. As we know that oim has some sequence to run processes that will end in Java. For the best practice, where and when should I create the log? Should I create log inside each function called by oim adapter? If I make a sysout at the beginning of function, parameter names and values, e.getMessage() inside catch(Exception e) and at the end of function, is it okay? Or is there any better implementation? Using sysout or log4j, commons logging, etc.
    in my idea (in each function):
    <function_name>::BEGIN
    - Time: <dd-MMM-yyyy>
    <function_name>::PARAMETER
    - <param_name1>: <param1_value>
    - <param_name2>: <param2_value>
    - <param_name3>: <param3_value>
    if error, inside throw{}
    <function_name>::ERROR
    - Message: <e.getMessage()>
    <function_name>::END
    is it good?

    This is what i've been doing with 11g logging.  In every custom code class i run, i use this to declare my logger:
    private final static Logger LOGGER = Logger.getLogger(<Class_Name>.class.getName().toUpperCase());  // Replace <Class_Name> with the actual class name
    This lets me go go the enterprise manager and make changes to the logging level once the class has been used.
    You can then use the following code:
    LOGGER.log(Level.INFO, "Insert Information Message Here");
    LOGGER.log(Level.CONFIG, "Insert More Detailed Debugger Information Message Here");
    LOGGER.log(Level.WARNING, "Insert Error Message Information Here", e); //e is your exception that is caught
    Personally, i like to put a start and end output in my logging, and then any details in the middle, i use the CONFIG level.  This lets me know pieces are running successfully, and only need to see the details during testing or if needed.  When deployed to production, i set the logger to WARNING level to only know about the problems.
    By using these, you can set your logger appropriately in the enterprise manager to output more detailed when needed.
    -Kevin

  • Flex best practices

    Im new to Flex but I have plenty of experience using traditional webdev technologies (HTML, CSS, JS/AJAX, PHP).  I know that when you build a web app using these technologies, it's considered best practice to use event listeners rather than event handlers in JS, and to place all your JS in an external file and reference it in your HTML page. I've been watching several videos on Lynda.com on Flash Builder 4 and Flex, and in all the videos, the author places most of the Actionscript in the MXML file while referencing a few custom Actionscript classes. With that said, what do Flex developers typically do?

    In Flex 3, it is considered best practice to use the Presentation Model pattern (as advocated by Martin Fowler), where you extract the view states and view logic.
    A PM is a simple ActionScript class that extends EventDispatcher (for Data Binding purposes).
    [Bindable]
    public class SalesProjectionPM extends EventDispatcher {
         // Collection of QuarterlySales objects
         public class quarterlySales:ArrayCollection;
         // Event handler
         public function viewSwitchHandler(event:MouseEvent):void {}
    You can then inject this PM into an MXML view using an IoC container framework and bind your view to the corresponding PM for both your components dataProviders and events. If you have a central data model, you can inject it into your PM and bind to it.
    In Flex 4, you already have the separation of view and logic that comes with the new Spark Architecture. You have an ActionScript component that contains the view states and view logic (including event handlers) on the one side. And you have a MXML skin that materializes the UI on the other.
    You add/remove event handlers in the partAdded(), partRemoved() overriden methods. If you have a central data model, you can inject it into your ActionScript components.

  • Best Practice for Storing Sharepoint Documents

    Hi,
    Is there a best practice where to store the documents of a Sharepoint? I heard some people say it is best to store sharepoint documents directly into file system. Ohters said that it is better to store sharepoint documents into a SQL Server.

    What you are referring to is the difference between SharePoint's native storage of documents in SQL, and the option/ability to use SQL's filestream functionality for Remote BLOB Storage (also known as RBS). Typically you are much better off sticking with
    SQL storage for BLOBs, except in a very few scenarios.
    This page will help you decide if RBS is right for your scenario:
    https://technet.microsoft.com/en-us/library/ff628583.aspx?f=255&MSPPError=-2147217396
    -Corey

  • Webaccess Domain Best Practice

    With GroupWise 8, best practice was to put the Webaccess domain on the same server as Webaccess. While designing our GW 2014 system security is much more important. In efforts to make GroupWise more secure, I don't think I like the idea any longer putting a secondary domain on a host that has direct internet access.
    What are other people doing?

    Thanks
    >>> On 2/2/2015 at 3:56 PM, magic31<[email protected]> wrote:
    kwhite;2345909 Wrote:
    > With GroupWise 8, best practice was to put the Webaccess domain on the
    > same server as Webaccess. While designing our GW 2014 system security
    > is much more important. In efforts to make GroupWise more secure, I
    > don't think I like the idea any longer putting a secondary domain on a
    > host that has direct internet access.
    >
    > What are other people doing?
    In short, no need for a secondary domain on the WebAccess server. I
    haven't done so since GroupWise 2012. As a note, it was not a necessity
    with GroupWise 8 and lower, as you could install the WebAccess agent on
    a server that was running on the LAN, and only install the
    WebApplication on the server in the DMZ.
    One main thing that has changed with WebAccess, as of GroupWise 2012, is
    that the WebAccess application doesn't make use of gwinter anymore
    (meaning there's no more Web Access agent component in 2012 and 2014).
    It's now a standalone (client) component that talks directly to the
    POA(s).
    So all you need is a SLES or Windows server in the DMZ and install and
    configure the WebAccess component on that.
    There are also no more eDir counterparts for WebAccess. All that is
    needed is a port opened to the POA's (for SOAP, which defaults to 7191)
    and since 2014 also port 8500 needs to be opened from POA(s) to the
    server running WebAccess. 8500 is needed for the auto refresh
    functionality that's new in WebAccess 2014.
    Cheers,
    Willem
    Knowledge Partner (voluntary sysop)
    magic31's Profile: https://forums.novell.com/member.php?userid=2303
    View this thread: https://forums.novell.com/showthread.php?t=481627

  • Where to put Concurrent Manager?

    Hello,
    We are currently running our production EBS (11.5.10.2) as a 2-Tier system on 32 bit Red Hat Linux. We have Web, Forms, Discoverer running on one server and Concurrent Manager, Admin and Database running on another. We will be upgrading the database server to RAC and would like to change to 64 bit.
    Also we will be running multiple app servers using shared appl top. Since we cannot leave the Concurrent Manager on the database server once it is 64 bit how to best decide where to put the Concurrent Manager?
    I know a couple of options are:
    1) Run the Concurrent Manager on a standalone server (no redundancy).
    2) Run the Concurrent Manager on 2 standalone servers using Parallel Concurrent Processing (provide redundancy but increase costs/maintenance).
    3) Run the Concurrent Manager on the same servers as the Web, Forms, Discoverer using shared appl top.
    I'm leaning towards option 3 but would like to hear others opinions. Could we still use PCP in this scenario? Any reasons not to do # 3?
    Thanks,
    Alfredo

    How many servers will you be running?I believe we have 4 total available for the Application Tier. They are fairly robust servers (HP DL-580 (4 CPU each) with 24 Gig of RAM).
    I have not seen PCP with Shared APPL_TOP. If you are running multiple Web, Forms, Discoverer servers, it is a good option to run them with their own APPL_TOP and run PCP with hardware based load balancing. Can we just skip PCP and run the 4 servers with Shared APPL_TOP but include everything on the Shared APPL_TOP (Web, Forms, Discoverer, Concurrent Manager)?
    I'm trying to do these upgrades in phases and I'm thinking maybe we can get 2 additional servers later and implement PCP then (keeping the 4 Apps servers for Web, Forms, Discoverer).
    Thanks,
    Alfredo

  • Where to put java code - Best Practice

    Hello. I am working with the Jdeveloper 11.2.2. I am trying to figure out the best practice for where to put code. After reviewing http://docs.oracle.com/cd/E26098_01/web.1112/e16182.pdf it seemed like the application module was the preferred spot (although many of the examples in the pdf are in main methods). After coding a while though, I noticed that there were quite a few libraries imported, and wondered whether this would impact performance.
    I reviewed postings on the forum, especially Re: Access service method (client interface) programmatically . This link mentions accessing code from a backing bean -- and the gist of the recommendations seems to be to use the data control to drag it to the JSF, or use the bindings to access code.
    My interest lies in where to put java code in the first place; In the View Object, Entity Object, and Am object, backing bean.....other?
    I can outline several best guesses about where to put code and the pros and cons:
    1. In the application module
    Pros: Centralized location for code makes development and support more simple as there are not multiple access points. Much like a data control centralizes services, the application module can act as a conduit for different pieces of code you have in objects in your model.
    Cons: Everything in one place means the application module becomes bloated. I am not sure how memory works in java -- if the app module has tons of different libraries are they all called when even a simple query re-execute method is called? Memory hog?
    2. Write code in the objects it affects. If you are writing code that accesses a view object, write it in a view object. Then make it visible to the client.
    pros: The code is accessed via fewer conduits (for example, I would expect that if you call the application module from a JSF backing bean, then the application module calls the view object, you have three different pieces of code --
    conts: The code gets spread out, harder to locate etc.
    I would greatly appreciate your thoughts on the matter.
    Regards,
    Stuart
    Edited by: Stuart Fleming on May 20, 2012 5:25 AM
    Edited by: Stuart Fleming on May 20, 2012 5:27 AM

    First point here is when you say "where to put the java code" and you're referring to ADF BC, the point is you put "business logic java code" in the ADF Business Components. It's fine of course to have Java code in the ViewController layer that deals with the UI layer. Just don't put business logic in the UI layer, and don't put UI logic in the model layer. In your 2 examples you seem to be considering the ADF BC layer only, so I'll assume you mean business logic java code only.
    Meanwhile I'm not keen on the term best practice as people follow best practices without thinking, typically best practices come with conditions and people forget to apply them. Luckily you're not doing that here as you've thought through the pros and cons of each (nice work).
    Anyway, back on topic and off my soap box, as for where to put your code, my thoughts:
    1) If you only have 1 or 2 methods put it in the AppModuleImpl
    2) If you have hundreds of methods, or there's a chance #1 above will morph into #2, split the code up between the AppModuleImpl, ViewImpl and ViewRowImpls. Why? Because your AM will become overloaded with hundreds of methods making it unreadable. Instead put the code where it should logically go. Methods that work on a specific VO row go into the associated ViewRowImpl, methods that work across rows in a VO go into the ViewImpl, and methods that work across VOs in the associated AppModuleImpl.
    To be honest which you ever option you choose, one thing I do recommend as a best practice is be consistent and document the standard so your other programmers know.
    Btw there isn't an issue about loading lots of libraries/imports into a class, it has no runtime cost. However if your methods require lots of class variables, then yes this will have a memory cost.
    On a side note if you're interested in more ideas around how to build ADF apps correctly think about joining the "ADF EMG", a free online forum which discusses ADF architecture, best practices (cough), deployment architectures and more.
    Regards,
    CM.

  • Root guard best practices? Where to put it?

    Hey all,
    We recently implemented root guard on our two core devices, on both ports that point to our distribution layer.  This broke the link from our secondary router to the distribution layer, which remains in a BKN state due to the root BPDU that passes through our distribution layer and into the router.  After doing this, we are now unable to pass traffic inbound from our secondary router.
    I'm wondering what would be considered a best practice with root guard -- should we leave it where it is, or push it down to the distribution layer where the interfaces connect to our access switches? Topology attached here.
    I will note that we are only allowing what vlans we need across each link, and currently we are not allowing all vlans across the trunk between R1 and R2.

    Hello Patrick-
    You should have root guard enabled on:
    - Core ports that are connecting to the distribution switches
    - Distribution ports that are connecting to the access switches
    Similar to this diagram (I was going to draw one but a quick google search got me one :) )
    http://www.rogerperkin.co.uk/ccie/wp-content/uploads/2013/03/spanning-tree-root-guard.jpg
    Also, what is the reason for not allowing all VLANs on the link between the core switches? Ideally, you would not want to block on that link. This can also (depending on actual setup) cause some traffic to be send to a blackhole if certain links are to die off. If the diagram that you attached is accurate then you would probably want to:
    - Connect each distribution switch to each core (create triangle type connections not squares)
    - Remove the link between distribution switches (optional but IMO preferred)
    - Allow all VLANs on the link between the two core switches
    - Let STP blocking happen on the link that is between the distribution and core switches while the link between the two cores remain in unblocking state
    Thank you for rating helpful posts!

  • When I share a file to YouTube, where does the output file live? I want also to make a DVD. And is this a best practice or is there a better way?

    I want also to make a DVD, but can't see where the .mov files are.
    And is this a best practice or is there a better way to do this, such as with a master file?
    thanks,
    /john

    I would export to a file saved on your drive as h.264, same frame size. Then import that into youtube.
    I have never used FCP X to make a DVD but I assume that it will build the needed vob mpeg 2 source material for the disk.
      I used to use Toast & IDVD. Toast is great.
    To "see" the files created by FCP 10.1.1 for YouTube, rt. (control) click on the Library Icon in your Movies/show package contents/"project"/share.

  • Best practice for putting together scenes in a Flash project?

    Hi, I'm currently working on a flash project with the following characteristics:
    using a PC
    2048x1080 pixels
    30 fps
    One audio file that plays (once) continuously across the whole project
    there are actions that relate to the audio, so the timing is important
    at least 10 scenes
    about 7 minutes long total
    current intent is for it to be played in a modern theater as a surprise
    What is the best practice for working on this project and then compiling it together?
    Do it all in one project file?
    Split the work into different project (xfl) files for each scene and then put it together when all the scenes are finalized?
    Use one project file but create different "scenes" for each respective scene?  I think this is the "classic" way (?).
    Make the scenes "movie clips" and then insert them into the timeline with the audio as its own layer?
    Other?
    I'm currently working on it by having it all in one project file.  But I've noticed that there's some lag (or it gets choppy) at certain parts during playback and the SWF history shows 3.1 MB with a yellow triangle with exclamation point symbol.  Thanks in advance. 

    you would only do that if it makes your job easier.  generally speaking, it would not.
    when trying to sync sound and animation i think most authors find it easiest to use graphic symbols because you can see their animation when scrubbing the main timeline.  with movieclips you only see their animation when testing.
    however, if you're going to use actionscript to control some of your symbols, those symbols should be movieclips.

  • Best practice for listeners for multiple oracle homes - 1 listener?

    I have a machine with 9i and 10g on it, and I have set up a 10g listener to serve connections to the 9i and 10g databases.
    Is this best practice, or is it better to have two listeners - a 9i listener for th 9i databases and a 10g listener for the 10g databases?

    HI,
    Are they two production databases ? In this case, like Laurent said, perhaps it's better to have one listener per instance, if one shutdown, it doesn't disturbe the other.
    Are they different application level (1 for dev, 1 for validation...), here too, perhaps it's better to have one listener per instance, if one shutdown, it doesn't disturbe the other.
    Are they two development databases ? In this case, you can to have one listener for all databases
    I don't think that there is only one way, but there is too many configuration which make one solution is better that other.
    Nicolas.

Maybe you are looking for