import java.awt.*;
import java.awt.event.*;
public class Button extends Frame implements ActionListener
{
Button rb, gb, bb; // create 3 button var
public ButtonDemo()
{
FlowLayout fl = new FlowLayout(); // choose any layout i choose flow layout
setLayout(fl);
rb = new Button("Red");. // map variables to objects
gb = new Button("Green");
bb = new Button("Blue");
rb.addActionListener(this); // link the listener with the button
gb.addActionListener(this);
bb.addActionListener(this);
add(rb); // add button to frame
add(gb);
add(bb);
setTitle("Buttons Created");
setSize(300, 350); // size of frame
setVisible(true); // to make frame visible on screen
}
// override the only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand(); // to know which Java button user clicked
System.out.println("You clicked " + str + " button"); // just beginner's interest
if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}
public static void main(String args[])
{
new ButtonDemo(); // anonymous object of ButtonDemo just to call the constructor
} // as all the code is in the constructor
}
import java.awt.event.*;
public class Button extends Frame implements ActionListener
{
Button rb, gb, bb; // create 3 button var
public ButtonDemo()
{
FlowLayout fl = new FlowLayout(); // choose any layout i choose flow layout
setLayout(fl);
rb = new Button("Red");. // map variables to objects
gb = new Button("Green");
bb = new Button("Blue");
rb.addActionListener(this); // link the listener with the button
gb.addActionListener(this);
bb.addActionListener(this);
add(rb); // add button to frame
add(gb);
add(bb);
setTitle("Buttons Created");
setSize(300, 350); // size of frame
setVisible(true); // to make frame visible on screen
}
// override the only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand(); // to know which Java button user clicked
System.out.println("You clicked " + str + " button"); // just beginner's interest
if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}
public static void main(String args[])
{
new ButtonDemo(); // anonymous object of ButtonDemo just to call the constructor
} // as all the code is in the constructor
}
No comments:
Post a Comment