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.
import java.awt.event.*;
import javax.swing.*;
public class Guitest { //class
public static void main(String[] args) { //main function
JFrame f=new JFrame("dog"); //creating frame object
final JLabel l1=new JLabel(""); //creating label object
l1.setBounds(150,50, 100,30); //set the label size
JButton b=new JButton("Doggy"); //creating button and set the text as doggy
b.setBounds(150,100,100,30); //set the button size
b.addActionListener(new ActionListener(){ //define event functon in the button object
public void actionPerformed(ActionEvent e){
l1.setText("Bow Bow."); //when the button will be clicked the function set the label text as Bow Bow
}
});
f.add(b);//adding button in the frame
f.add(l1); //adding label in the frame
f.setSize(400,400); //ste the size of frame
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit conditon
}
}
sampel output:-
i have use swing class for gui componants.
create a class and main function
then create the jframe object ans set the title from the constructer.
create the jlabel object and set the size of it.
create the jbutton object and ste the text using constructer
set the size of the button
then in button's event set the event that you want to perform when the button is clicked
add the button ,label in the frame
set f.setLayout(null) as we are not using any layout
f.setVisible(true); to show the frame
finaly the exit condition for closing the program