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:

 * Copyright (c) 1997-2018 All Rights Reserved.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonAction3 extends MouseAdapter {
   JButton myButton = null;
   JLabel myLabel = null;
   String text = null;
   public static void main(String[] a) {
      JButtonAction3 myTest = new JButtonAction3();
   public void createFrame() {
      JFrame f = new JFrame("My Switch Button");
      Container c = f.getContentPane();
      c.setLayout(new GridLayout(2,1));
      text = "On";
      myButton = new JButton(text);
      myLabel = new JLabel(text,SwingConstants.CENTER);
   public void mouseClicked(MouseEvent e) {
      if (text.equals("On")) text = "Off";
      else text = "On"; 

If you run this example, you will get:

JButton Button with Mouse Adapter
JButton Button with 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.

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

JButton - Swing Button Class

 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

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials


 Full Version in PDF/EPUB