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. ASAP
Code:
import java.awt.; //this package is used to create gui and components in java
import java.awt.event.; //this used to handle events from components
class Main extends Frame implements ActionListener{ //extend frame class to create window and addActionListener interface to handle events
Label l; //create lable object to display message on click
Button b; //create button for click event
Main(){ //constructor of class to initialize components
b=new Button("Doggy"); //initialize button with text Doggy
b.setBounds(175,150,60,30); //it used to specify where button should display
l=new Label(); //initialize lable
l.setBounds(180,200, 60,30);//it used to specify where label should display
b.addActionListener(this); //when button is clicked then actionPerformed method called automatically because we handled button event
l.setForeground(Color.RED); //set color of label text to red
add(b); //add button to the frame
add(l); //add Label to the frame
setSize(400,400); //specify size(height,width) of frame
setLayout(null);
setVisible(true); //here it used to visible frame to screen
}
public void actionPerformed(ActionEvent e) { //when button clicked event is handles here
try{
l.setText("Bow Bow"); //it sets this message to the label
}
catch(Exception ex)
{System.out.println(ex);}
}
public static void main(String[] args) {
new Main(); //create object of main class
}
}
Save file with Main.java
Then compile javac Main.java
Then run java Main
Output:
After Doggy button clicked: