Results 1 to 3 of 3
  1. #1
    Daniel is offline Member
    Join Date
    Jun 2007
    Posts
    91
    Rep Power
    0

    Default Help with Event Handlers

    Hi, can anybody explain me how Event Handlers works in Java or link me any tutorial?
    Thanks

    Daniel:o

  2. #2
    Eric is offline Senior Member
    Join Date
    Jun 2007
    Posts
    111
    Rep Power
    0

    Default

    Events in java are implemented via interfaces and/or inner class and interfaces.

    For example, if you have a button and you wish to add an onclick event handler for that button, than you write:

    Java Code:
    JButton button = new JButton( "Example" );
    button.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent event ) {
    JOptionPane.showMessageDialog( null, "This is an example" ) ;
    } } );
    In the above sample, we used an inner class to handle button clicks on the button instance of JButton. There are other events such as on focus etc...that can be implemented for JButton instances.

    If you want to implement an interfaces without declaring inner classes, than your main class must implement ActionListener interface and defines an actionPerformed method.

    For a good introductory tutorial on Events in Java, check out the Sun Microsystems tutorial...which provides a good hands on guide on how to implements events in java.

    http://java.sun.com/docs/books/tutor...nts/index.html

    Greetings.

    Eric

  3. #3
    Albert is offline Senior Member
    Join Date
    Jun 2007
    Posts
    114
    Rep Power
    0

    Default

    The other style that Eric mentions would look like this, either gets the job done so it's really just a matter of preference:

    Java Code:
    public class Example implements ActionListener
    {
        public Example()
        {
            JButton button = new JButton( "Example" );
            button.addActionListener( this );
        }
    
        public void actionPerformed( ActionEvent event ) {
            JOptionPane.showMessageDialog( null, "This is an example" ) ;
        }
    }
    Greetings

    Albert:rolleyes:

Similar Threads

  1. Event
    By nt5515 in forum New To Java
    Replies: 0
    Last Post: 02-15-2008, 04:44 PM
  2. Listener for SWT event
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-08-2008, 09:04 AM
  3. key pressed event
    By kavithas in forum New To Java
    Replies: 7
    Last Post: 12-10-2007, 02:01 PM
  4. Need help with JButton event
    By adlb1300 in forum New To Java
    Replies: 2
    Last Post: 11-19-2007, 01:15 AM
  5. Event Handling
    By luisarca in forum Sun Java Wireless Toolkit
    Replies: 5
    Last Post: 05-07-2007, 06:05 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
  •