
Please, could someone help me with how to use action listeners I am creating a gui with four buttons. I will like to know how to apply the action listener to these four buttons.

Hello Friend,
Try the following code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ButtonAction extends JFrame implements ActionListener{
JButton b1,b2,b3,b4;
ButtonAction(){
b1=new JButton("A");
b2=new JButton("B");
b3=new JButton("C");
b4=new JButton("D");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
JPanel p=new JPanel();
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e){
String choice=e.getActionCommand();
if(choice.equals("A")){
JOptionPane.showMessageDialog(null,"This is button A");
}
else if(choice.equals("B")){
JOptionPane.showMessageDialog(null,"This is button B");
}
else if(choice.equals("C")){
JOptionPane.showMessageDialog(null,"This is button C");
}
else if(choice.equals("D")){
JOptionPane.showMessageDialog(null,"This is button D");
}
}
public static void main(String[] args){
new ButtonAction();
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.