Java Program using JButton with ActionListener


In this program, You will learn how to implement JButton with ActionListener in java.


public void actionPerformed(ActionEvent e) { 
     //statement
}

Example: How to implement JButton with ActionListener in java.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

class Test extends JFrame implements ActionListener {

    JButton jb1;
    JTextField jt;

    Test() {
        jt = new JTextField();
        jt.setBounds(50, 30, 150, 30);
        add(jt);

        jb1 = new JButton("Test it Now");
        jb1.setBounds(50, 200, 100, 30);
        add(jb1);

        jb1.addActionListener(this);

        setLayout(null);
        setSize(600, 400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        jt.setText("Welcome to Xiith");
    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

jButton