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.
Main.java
import java.awt.event.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
//Creates a new window
JFrame f=new JFrame("Doggy");
/* To display message 'Bow Bow' on button click
label is create */
JLabel l1;
l1=new JLabel();
//To place on the window coordinate and size it set
l1.setBounds(50,150, 100,30);
//Creates button name 'Doggy'
JButton b=new JButton("Doggy");
//To place on the window coordinate and size it set
b.setBounds(50,100,95,30);
//On button click function will called to display message
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//This message will be added to created label and display on the window
l1.setText("Bow Bow");
}
});
//button and label are added to created window
f.add(b); f.add(l1);
//Setting size of the window
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Code Snippet (For Indentation):
Output: