Is this your first time here? SwingWiki is a Java Swing Developer community site with an big archive of Swing-related usenet groups and mailing lists, but also tips, tricks and articles and book reviews written by your colleagues from around the world. If you came here through a search engine and did not find what you were looking for, make sure to check the wiki table of contents.

Event handling and processing

In Swing/AWT you have a multiple options when dealing with events. Here are a few examples.

1. You can implement a listener anonymously.

  clearButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
       JOptionPane.showMessageDialog(null , "Clicked!");
    }
  });

This can be very nice when you just want to relay to another method. This option often leaves logic right in the GUI code.

2. You can create a new named class to handle events.

public class MyEventHandler implements MouseListener
{
  private View view;
  
  public MyEventHandler(View view)
  {
    this.view = view;
  }
  
  public void mouseClicked(MouseEvent e)
  {
    System.out.println("Clicked");
    
    JButton button = (JButton)e.getSource();
    if(button == view.startButton)
    {
      start();
    }
    else if(button == view.stop)
    {
      stop();
    }
    else
    {
      restart();
    }
  }
  public void mousePressed(MouseEvent e)
  {
    System.out.println("Pressed");
  }
  public void mouseReleased(MouseEvent e)
  {
    System.out.println("Released");
  }
  public void mouseEntered(MouseEvent e)
  {
    System.out.println("Entered");
  }
  public void mouseExited(MouseEvent e)
  {
    System.out.println("Exited");
  }
  
  // add other methods to assist event handling //
  
}

This class can be used to handle events for multiple components.

 

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  other/event_handling.txt · Last modified: 2006/05/26 20:55 by 208.3.82.178 (mohadib)
 
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register | The Quest For Software++| Ruby Resources

Sedo - Buy and Sell Domain Names and Websites project info: swingwiki.org Statistics for project swingwiki.org etracker� web controlling instead of log file analysis