Using setActionCommand In Java NetBeans
_______________________________________________________________________________
In this java Collection Tutorial we will see How To Use setActionCommand With Button
In Java NetBeans .
Source Code:
package JavaDB_001;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Project extends JFrame {
JButton btnOK,btnYES,btnNO;
public Project(){
btnOK = new JButton("OK");
btnYES = new JButton("YES");
btnNO = new JButton("NO");
btnOK.setActionCommand("OK");
btnYES.setActionCommand("YES");
btnNO.setActionCommand("NO");
btnOK.addActionListener(new BtnAction());
btnYES.addActionListener(new BtnAction());
btnNO.addActionListener(new BtnAction());
btnOK.setBounds(20, 20, 100, 20);
btnYES.setBounds(140, 20, 100, 20);
btnNO.setBounds(260, 20, 100, 20);
add(btnOK);
add(btnYES);
add(btnNO);
setLayout(null);
setSize(400, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.decode("#bdb76b"));
setVisible(true);
}
public class BtnAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("OK")){
JOptionPane.showMessageDialog(null, "CLICK OK");
}
if(s.equals("YES")){
JOptionPane.showMessageDialog(null, "CLICK YES");
}
if(s.equals("NO")){
JOptionPane.showMessageDialog(null, "CLICK NO");
}
}
}
public static void main(String[] args){
new Project();
}
}