Java Program to create multiple JButton with ActionListener


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


JButton jb1, jb2

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

Example: How to create multiple 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, jb2;
    JTextField jt;

    Test() {

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

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

        jb2 = new JButton("CHINA");
        jb2.setBounds(180, 200, 100, 30);
        add(jb2);

        jb1.addActionListener(this);
        jb2.addActionListener(this);

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

    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource().equals(jb1)) {
            jt.setText("USA");
        } else if (e.getSource().equals(jb2)) {
            jt.setText("CHINA");
        }
    }

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

Output:

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.