Button control in java

Button control

Push Button

  • A push button is a component that contains a label & that generates an event when it is pressed
  • Push buttons are objects of type Button
  • Constructors
    Button( )
    Button(String str)
  • Methods
    void setLabel(String str)
    String getLabel()
Example
import java.awt.*;
import java.awt.event.*;
class test extends Frame implements ActionListener
{
Button b1,b2,b3;
test()
{
this.setLayout(null);
b1 = new Button(“yellow”);
b2=new Button(“blue”);
b3=new Button(“pink”);
b1.setBounds(100,100,70,40);
b2.setBounds(100,160,70,40);
b3.setBounds(100,220,70,40);
this.add(b1);
this.add(b2);
this.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals(“yellow”))
this.setBackground(Color.yellow);
if(str.equals(“blue”))
this.setBackground(Color.blue);
if(str.equals(“pink”))
this.setBackground(Color.pink);
}
public static void main(String args[])
{
test t = new test();
t.setSize(400, 400);
t.setTitle(“My Button”);
t.setVisible(true);
}
}

Output:
Untitled

Radio Button

A radio button represents a round shaped button.
Only one can be selected from a group of buttons.
Radio button can be created using CheckboxGroup class and Checkbox classes.

Example

import java.awt.*;
import java.awt.event.*;

import org.omg.CORBA.Current;
class test extends Frame implements ItemListener
{
String msg=” “;
CheckboxGroup cbg;
Checkbox y,n;
test()
{
setLayout(new FlowLayout());
cbg = new CheckboxGroup();
y = new Checkbox(“yes”, cbg ,true);
n = new Checkbox(“no”,cbg,false);
add(y);
add(n);
y.addItemListener(this);
n.addItemListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg=”Current selection: “;
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 10, 100);
}
public static void main(String args[])
{
test t = new test();
t.setTitle(“My Radio Button”);
t.setSize(400, 400);
t.setVisible(true);
}
}

Output:
Untitled

Leave a Reply

Your email address will not be published. Required fields are marked *