Monday, October 24, 2016

How to write Action Listener for a JButton(Swing JButton Event)

import javax.swing.*;
import java.awt.*;

class MyFrame extends JFrame {
JButton btn=new JButton("click");
Container c;
MyFrame()
{
c=this.getContentPane();
c.setLayout(null);
btn.setBounds(100,50,100,50);
c.add(btn);
}
}
class AcionDemo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("ActionDemo");
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(100,50,700,500);
}
}

/**OutputScreen*/


















/** 
 * simply displays Diffrent Button Color Using ActionListener.
 */
import javax.swing.*;
import java.awt.*; import java.awt.event.*; class MyFrame extends JFrame implements ActionListener { JButton btn1=new JButton("RED"); JButton btn2=new JButton("YELLOW"); JButton btn3=new JButton("GREEN"); JButton btn4=new JButton("BLACK"); JButton btn5=new JButton("BLUE"); JButton btn6=new JButton("GRAY"); Container c; MyFrame() { c=this.getContentPane(); c.setLayout(null); btn1.setBounds(100,50,100,50); btn2.setBounds(200,50,100,50); btn3.setBounds(300,50,100,50); btn4.setBounds(400,50,100,50); btn5.setBounds(500,50,100,50); btn6.setBounds(600,50,100,50); btn1.addActionListener(this); btn2.addActionListener(this); btn3.addActionListener(this); btn4.addActionListener(this); btn5.addActionListener(this); btn6.addActionListener(this); c.add(btn1); c.add(btn2); c.add(btn3); c.add(btn4); c.add(btn5); c.add(btn6); } public void actionPerformed(ActionEvent e) { //c.setBackground(Color.YELLOW); if(e.getSource()==btn1) { c.setBackground(Color.RED); } if(e.getSource()==btn2) { c.setBackground(Color.YELLOW); } if(e.getSource()==btn3) { c.setBackground(Color.GREEN); } if(e.getSource()==btn4) { c.setBackground(Color.BLACK); } if(e.getSource()==btn5) { c.setBackground(Color.blue); } if(e.getSource()==btn6) { c.setBackground(Color.gray); } } } class AcionDemo { public static void main(String[] args) { MyFrame f=new MyFrame(); f.setTitle("ActionDemo"); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setBounds(100,50,700,500); } }

//*OutputScreen*/
















No comments:

Post a Comment