In: Computer Science
Write Java code which will create a GUI window on screen. The window has one button: Doggy. When the user selects Doggy, “Bow Bow” should be printed on screen. Justify your syntax.
CODE IS PROVIDED WITH COMMENTS
CODE:
import javax.swing.*; //importing all the classes from swing
import java.awt.*; //importing all the classes from awt
import java.awt.event.*; //importing all the classes from sub package event
public class Doggy implements ActionListener //implementing the interface ActionListener
{
Frame f;
Button b; //creating the instances
Label label;
Doggy() //constructor of Doggy class
{
f=new Frame("Button"); //giving a name to the frame
b=new Button("Doggy"); //giving a name to the button
label=new Label();
f.add(b); //adding the button object to frame
f.add(label); //adding the label to the frame
b.addActionListener(this);
f.setLayout(new FlowLayout(FlowLayout.CENTER,50,20)); //setting the layout
f.setSize(300,200); //setting the frame dimensions
f.setVisible(true); //making it visible
}
public void actionPerformed(ActionEvent ae) //method to create an action to the button
{
if(ae.getActionCommand().equals("Doggy"))
{
label.setText("BOW BOW"); //setting an action to get printed
f.add(label); //adding that label to the frame
f.setVisible(true);
}
}
public static void main(String args[]) //main method
{
new Doggy();
}
}
OUTPUT: