Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

Mouse Click Handler at the Frame Level

This section provides a tutorial example on how to create a button to handle actions by adding the MouseAdapter interface to the frame that contains the button component.

Of course, using ActionListeners is not the only way to handle user clicks on buttons. You can also use MouseListeners to handle user clicks. Here is an example program:

/**
 * JButtonAction3.java
 * Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonAction3 extends MouseAdapter {
   JButton myButton = null;
   JLabel myLebal = null;
   String text = null;
   public static void main(String[] a) {
      JButtonAction3 myTest = new JButtonAction3();
      myTest.createFrame();
   }
   public void createFrame() {
      JFrame f = new JFrame("My Switch Button");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new GridLayout(2,1));
      text = "On";
      myButton = new JButton(text);
      myButton.addMouseListener(this);
      c.add(myButton);
      myLebal = new JLabel(text,SwingConstants.CENTER);
      c.add(myLebal);
      f.pack();
      f.setVisible(true);
   }
   public void mouseClicked(MouseEvent e) {
      if (text.equals("On")) text = "Off";
      else text = "On"; 
      myButton.setText(text);
      myLebal.setText(text);
   }
}

If you run this example, you will get:
JButton Button Mouse Adapter

The button works nicely. If you click the button, the button label text will change from "On" to "Off", and the text of the label component will also change.

Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.2, 1.5.0. and 1.6.0

Last update: 2009.

Sections in This Chapter

Creating Buttons with javax.swing.JButton Class

Creating Image Buttons with javax.swing.JButton Class

Button Action Handler at the Component Level

Button Action Handler at the Frame Level

Mouse Click Handler at the Frame Level

Dr. Herong Yang, updated in 2009
Mouse Click Handler at the Frame Level