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.
Using ActionListner, string will be printed.
On button click value of i variable will be changed and based on i variable string will be displayed.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener
{
//on button clock i var will changed
int i=0;
//string to print on screen
String s="Bow Bow";
//button declaration
Button d;
public static void main(String[] args)
{
//craetes object of class
new Main("Doggy Button");
}
public Main(String title)
{
//sets title, size of a dialog
super(title);
setSize(300,400);
setVisible(true);
d = new Button("Doggy"); // new Button doggy
/*Default layer of frame is border layout so add in south*/
add("South",d);
//when action is performed, this event will be called
d.addActionListener(this);
//To close the window with close button
//windowadapter
addWindowListener(new WindowAdapter()
{
//handling close button of dialog
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
//If button got presssed then print the string by matching button name
String str = e.getActionCommand();
if(e.getSource() instanceof Button)
//if "Doggy" button is clicked, string will be printed and i var will change
if(str.equals("Doggy"))
{
//To print the string call repaint() method
i=1;
repaint();
}
}
//to display string on the screen on i variable
public void paint(Graphics g)
{
//Print the string
if(i==1)
g.drawString(s,125,200);
}
}
Please refer below ss for output
Outputs:
GUI display
When button is clicked