Buttons
Buttons provide an important facility that is used to perform an event. Button is a control component that generates events when it is pressed. At the time of creation of button, we mention the label to the button.Button class extends the Component class and implements the Accessible interface.
Button Class Constructors
i.) Button() - Creates button with empty string for its label.ii.) Button(String label) - Creates button with specified string.
Declaration of Button Class
public class Button
extends Component
implements Accessible
Creation of Button
For example:Button b;
b1 = new Button("OK");
b2 = new Button("Quit");
b3 = new Button("Submit;
Example: Creating buttons in AWT
import java.awt.*;
import java.awt.event.*;
class ButtonDemo extends Frame implements
ActionListener
{
Button button1, button2, button3;
public ButtonDemo()
{
setLayout(new FlowLayout());
button1 = new Button("Reset");
button2 = new Button("Submit");
button3 = new Button("Quit");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
add(button1);
add(button2);
add(button3);
setTitle("Buttons in AWT");
setSize(200, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
if(str.equals("Reset"))
setBackground(Color.red);
else if(str.equals("Submit"))
setBackground(Color.green);
else if(str.equals("Quit"))
setBackground(Color.blue);
System.exit(0);
}
public static void main(String args[])
{
new ButtonDemo();
}
}
Output:

JButton
JButton class provided by Swing is totally different from Button which is provided by AWT. It is used to add platform independent button in swing application. Swing buttons are extended from the AbstractButton class that is derived from JComponent.
AbstractButton class implements the Accessible interface.
Declaration of JButton Class
public class JButton
extends AbstractButton
implements Accessible
JButton Class Constructors
i.) JButton()ii.) JButton(Action a)
iii.) JButton(Icon icon)
iv.)JButton(String s)
v.) JButton(String s, Icon icon)
Creation of JButton
For example:JButton jb = new JButton("OK");
Example: Creating button in Swing.
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonDemo
{
JButtonDemo()
{
JFrame frame=new JFrame();
JButton b1 = new JButton("OK");
JButton b2 = new JButton("Quit");
b1.setBounds(50,50,90, 50);
b2.setBounds(150,50,90,50);
frame.add(b1);
frame.add(b2);
frame.setSize(300,200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JButtonDemo();
}
}
Output:



