JButton in Java Swing


Simple code for a Button in Java.

File:demo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class demo extends JFrame implements ActionListener{
JLabel l1;
JButton b1,b2;
demo()
{
super(“Button Example”);
setLayout(new FlowLayout());
b1=new JButton(“Clicked”);
getContentPane().add(b1);
b2=new JButton(“Not Clicked”);
getContentPane().add(b2);
l1=new JLabel(“”);
getContentPane().add(l1);
myadapter mine=new myadapter();
addWindowListener(mine);
b1.addActionListener(this);
b2.addActionListener(this);

}
public class myadapter extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
l1.setText(“Clicked label is triggerd”);
}
else
{
l1.setText(“Not Clicked label is triggerd”);
}
}
public static void main(String ar[])
{
demo d=new demo();
d.setSize(400,400);
d.setVisible(true);
}
}

Output looks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s