forked from Ashish8104/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButtonColor.java
More file actions
51 lines (45 loc) · 1.68 KB
/
ButtonColor.java
File metadata and controls
51 lines (45 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.awt.*;
import java.awt.event.*;
public class ButtonColor extends Frame implements ActionListener
{
Button rb, gb, bb; // three Button reference variables
public ButtonColor() // constructor to set the properties to a button
{
FlowLayout fl = new FlowLayout(); // set the layout to frame
setLayout(fl);
rb = new Button("Red"); // convert reference variables into objects
gb = new Button("Green");
bb = new Button("Blue");
rb.addActionListener(this); // link the Java button with the ActionListener
gb.addActionListener(this);
bb.addActionListener(this);
add(rb); // add each Java button to the frame
add(gb);
add(bb);
setTitle("Button in Action");
setSize(300, 350); // frame size, width x height
setVisible(true); // to make frame visible on monitor, default is setVisible(false)
}
// 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 ButtonColor(); // anonymous object of ButtonDemo just to call the constructor
} // as all the code is in the constructor
}