Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add Event Handling to a Button in Java using Swing API

Program to demonstrate event handling in a Swing Button.
package com.hubberspot.awtSwing.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ButtonEventHandling implements ActionListener
{
  JFrame frame;
  JButton button;
  JTextField textField;

  ButtonEventHandling()
  {
    frame=new JFrame("Welcome to Hubberspot");
    frame.setLayout(new FlowLayout());
    button=new JButton("Like Us!");
    textField=new JTextField(20);

    button.addActionListener(this);

    frame.setSize(100,100);
    frame.add(textField);
    frame.add(button);

    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  } 

  public void actionPerformed(ActionEvent ae) 
  {
    textField.setText("Thanks for liking Hubberspot!");
  } 

  public static void main(String[] args)
  {
    new ButtonEventHandling();
  }
}
Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot