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.
//Java Code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
public class DoggyGUI extends JFrame implements ActionListener {
//Create a label
JLabel lblResult;
//create a button
JButton btnShow;
public DoggyGUI()
{
lblResult = new JLabel("");
lblResult.setBounds(120,50,80,30);
btnShow = new JButton("Doggy");
//set Action listener
btnShow.addActionListener(this::actionPerformed);
btnShow.setBounds(100,100,80,30);
setLayout(null);
setTitle("Doggy GUI");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add label to Frame
getContentPane().add(lblResult);
//Add button to Frame
getContentPane().add(btnShow);
setVisible(true);
}
//Action listener
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(btnShow))
{
//set label text
lblResult.setText("Bow Bow");
}
}
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
new DoggyGUI();
}
});
}
}
//Output
//If you need any help regarding this solution....... please leave a comment.. thanks