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.
//create a class with name BarkingDog.java and paste the code given below
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class BarkingDog {
BarkingDog(){
JFrame f=new JFrame("Barking Dog");
//create a button
JButton button=new JButton("Doggy");
//set button bounds on window
button.setBounds(100,100,140, 40);
//empty label which will show event after button clicked
JLabel label = new JLabel();
//set label bounds on window
label.setBounds(100, 10, 200, 100);
//add label
f.add(label);
//add button
f.add(button);
//set size for frame
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
//set close operation
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//action listener
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//after clicking button should print on window
label.setText("Bow Bow");
}
});
}
public static void main(String[] args) {
//create a object of class
new BarkingDog();
}
}
//output