Wednesday, 7 October 2015

Create Button and add ActionListener to the button in Java

Requirement: Write a Java program to create a button Morning. When the user click on the Morning button, the message "Good morning to you" should appear in a popup.

Solution: The Java program for the above requirement is shown below:

Java Program:
package com.susanto;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class ClassName extends JFrame {
      private JButton button;

      public ClassName() {
            JPanel p = new JPanel();
            button = new JButton("Morning");
            p.setLayout(null);
            button.setBounds(30, 100, 100, 30);
            p.add(button);
            button.addActionListener(new ActionListener() {

                  public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(null, "Good morning to you.");
                  }
            });
            getContentPane().add(p);
            setDefaultCloseOperation(3);
            setSize(1100, 600);
            setVisible(true);
      }

      public static void main(String... args) {
            new ClassName();
      }
}


Output:
When we run the above program we get the below screen.

When we click on the Morning button we get the popup message "Good morning to you" as shown below:



Thanks & Regards,
Susanto Paul