Week 1 - GUI Programming - Swing & AWT Components
Week 1 - GUI Programming - Swing & AWT Components
In Java, Graphical User Interface (GUI) programming allows developers to create interactive
applications where users can interact with graphical elements like buttons, text fields, labels,
and more. There are two main libraries used for GUI programming in Java:
2. Swing: A more modern, versatile, and lightweight toolkit built on AWT, which
provides a richer set of GUI components.
AWT vs Swing
AWT Swing
Limited features and flexibility Provides more components and features (e.g.,
tables, trees, sliders)
Rich Component Set: Swing includes components not found in AWT, such as JTable,
JTree, and JSlider.
Pluggable Look-and-Feel: The look and feel of Swing applications can be changed at
runtime without changing the code.
Example:
Example:
Example:
Example:
6. Layout Managers: Swing provides various layout managers to control how components
are arranged, such as:
Here’s a basic example of a Swing application that creates a window with a button and a
label.
In Swing, events occur when users interact with the GUI (e.g., clicking a button). Event
handling is a mechanism that catches these events and processes them.
3. Listener: Receives the event and processes it. It must implement the appropriate
interface (e.g., ActionListener for button clicks).
Objective: Create a Java application with a JFrame containing a JLabel and a JButton.
When the button is clicked, the label text should change.
Steps:
3. Use an ActionListener to detect when the button is clicked and update the
label’s text.
Expected Output: A window with a button and a label. Clicking the button changes
the label’s text.
Objective: Create a GUI application where you have a JPanel containing multiple
components (a label, a text field, and a button).
Steps:
4. Add an event handler that changes the text of the JLabel when the button is
clicked.
Expected Output: A window with a panel. The panel contains a label, text field, and
button. Clicking the button changes the label’s text.
Objective: Modify the layout of a simple Swing application using different layout
managers.
Steps:
2. Add at least three components to each layout and see how they arrange.
Advanced Reading
Recommended Books
Conclusion
In Week 1, we have introduced GUI programming using Java's Swing and AWT toolkits. You
have learned how to create simple GUI applications, use basic components like JLabel,
JButton, and JTextField, and handle user interactions using event listeners. You are
encouraged to practice the exercises to solidify your understanding.