View Single Post
  #2 (permalink)  
Old 09-24-2007, 09:07 AM
ElPolloDiablo ElPolloDiablo is offline
Newbie
 
Join Date: Sep 2007
Location: Oudenaarde, Belgium
Age: 25
Posts: 1
Rep Power: 0
ElPolloDiablo is on a distinguished road
Send a message via MSN to ElPolloDiablo
Default

It might also be interesting to explain its derived adapter class.

The MouseListener interface has an abstract class implementation called MouseAdapter.

The advantage of using the adapter class instead of the interface is that when you only need one method (say, mouseClicked, as in the final example), you don't need to implement the other ones.

The code, when using MouseAdapter, would then look like this:
Java5 Code:
  1. package tutorials;
  2. import java.awt.FlowLayout;
  3. import java.awt.event.MouseEvent;
  4. import java.awt.event.MouseAdapter;
  5. import javax.swing.JButton;
  6. import javax.swing.JFrame;
  7. import javax.swing.JLabel;
  8. public class MouseMethods extends MouseAdapter {
  9.  
  10.           private JLabel label = new JLabel("This is a JLabel");
  11.           private JButton button = new JButton("This is a JButton");
  12.  
  13.           public MouseMethods() {
  14.               JFrame frame = new JFrame("MouseMethods");
  15.               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  16.               frame.setLayout(new FlowLayout());
  17.               label.addMouseListener(this);
  18.               button.addMouseListener(this);
  19.  
  20.               frame.add(label);
  21.               frame.add(button);
  22.               frame.setVisible(true);
  23.               frame.pack();
  24.           }
  25.        
  26.           public void mouseClicked(MouseEvent e) {
  27.               if(e.getSource().equals(button)){
  28.                   System.out.println("The JButton was clicked...");
  29.               } else if(e.getSource().equals(label)){
  30.                   System.out.println("The JLabel was clicked...");
  31.               } else {
  32.                   System.out.println("Something else was clicked...");
  33.               }
  34.           }
  35.  
  36.           public static void main(String args[]) {
  37.               new MouseMethods();
  38.           }
  39. }
Reply With Quote