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.
Here is your code:
import java.awt.*;
import java.awt.event.*;
public class dede {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Doggy");
Label l2=new Label("Bow Bow");
l2.setBounds(50,150, 100,30);
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
f.add(l2);
}
});
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Syntax justification:
The code is very simple we add a frame,a button "Doggy" and a label "Bow Bow". The label is only added to the frame if the button is clicked. The event used is actionPerformed. Since there is only one button we are sure that all actionEvent are from that button only, if there were multiple buttons we have to check for which button is clicked and take desired action accordingly.