University of Technology, Jamaica
School of Computing and Information Technology
Advanced Programming (CIT3009)
Tutorial Worksheet – Graphical User Interface (Part One)
Objectives:
✔ To give students a better understanding of working with the javax.swing
✔ To allow students to practice working with GUI components in the javax.swing package
Exercise One
1. Create a new Java Project called “GUIDemo”
2. Create a package called “com.gui_demo”
3. Create a class called “GUIDemo” with the main method in it
4. Use the following to import the javax.swing package:
import javax.swing.*;
5. Create a default constructor
6. Create the following attributes in the class:
• JFrame frame
• JButton button
7. In the constructor, initialize the attributes to new instances. For the JFrame use the pass
the string “GUI Demo - One” as argument to the constructor , and for the JButton pass
the string “Click me” as argument to its constructor
8. Next configure the JFrame with the following:
frame.setSize(400, 400);
frame.setLayout(null);
9. Configure the JButton with the following:
button.setBounds(130,100,100, 40);
10. Now add the button to the frame with the following code:
frame.add(button);
11. Now that the button has been added to the frame, make the frame visible with the
following line of code;
frame.setVisible(true);
12. In the main method create a new instance of the GUIDemo class:
new GUIDemo();
Created by:- Christopher O. Panther, October 7, 2020
13. Now run the program
Congratulations!! If you did everything correctly you would have created your first
GUI, and should see a window similar to the one shown in the image below:
14. Now close the window with the close icon ‘X’ at the top right hand corner of the
window.
15. In the are of your console you should be seeing something similar to the following
image
The red square is an indication that your program is still running even though you have
closed the window. To fix that add the following line of code to yor frame configuration:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16. Run the program again and note the difference when you close the window
Created by:- Christopher O. Panther, October 7, 2020
Exercise Two:
1. Create a package called “com.gui_listener_demo”
2. Create a class called “GUIListenerDemo” with the main method in it
3. Repeat steps 4 to 9 from Exercise One
4. Add an action listener to the button using the following code:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "You clicked the
button", "Action Demo", JOptionPane.INFORMATION_MESSAGE);
}
});
5. Repeat steps 10 & 11 of Exercise One.
6. Add the default close operation to the frame (Step 15 of Exercise One)
7. In the main method create a new instance of GUIListenerDemo
8. Run the program.
Created by:- Christopher O. Panther, October 7, 2020