GUI Packages

  • GUI: Graphical User Interface

  • Packages:

    • AWT: Abstract Window Toolkit

      • Heavyweight, platform-dependent components generated by the system’s host

    • Swing

      • Lightweight, platform-independent components

      • We’ll focus on this package

    • JavaFX

      • Successor of Swing (though Swing isn’t obsolete)

      • As of JDK ~7, JavaFX was bundled; as of JDK 11, the modules are no longer bundled but open-sourced as Maven artifacts

      • We’ll not use JavaFX since we’re focusing on core Java (no Maven dependency)

Goal

  • Use and extend built-in UI classes to design our app’s view(s)

    • Code will be verbose, similar to HTML’s hierarchical structure

    • Instead of tags, we’ll use classes/objects

    • Swing components often correspond to HTML elements, prefixed with J

      • Example: <button> in HTML maps to JButton in Swing

  • Focus on layout managers, panels, and components

Hierarchy of Components

How to Start

  • Common strategies for GUI design:

    • Code in main() method

    • Code in constructor

    • Use inheritance (our approach in this course)

  • First example extends JFrame

    • Provides a window with a close button

    • Adds JTextField to display a message

      • JTextField needs dimension data since layout managers aren’t used initially

      • Without a layout manager, absolute positioning is applied

  • Steps to create the UI:

    • Add JTextField to JFrame using add() method

    • Define frame size and set visibility

      • A non-visible frame terminates the app

  • Ensure UI updates occur on the Event Dispatch Thread (EDT) using SwingUtilities.invokeLater

  • Code Example: MyFrame.java

Quick Note about Threads (EDT and Main)

  • Main Thread

    • Role: Starts Java app execution, runs main method

    • Lifecycle: Sets up initial state, creates and starts other threads

    • GUI Initialization: Creates initial GUI components, offloads updates to EDT

  • Event Dispatch Thread (EDT)

    • Role: Handles all GUI-related tasks (drawing components, handling events)

    • Thread Safety: Swing components aren’t thread-safe; access only via EDT

    • Event Handling and Rendering: GUI updates and event listeners should run on EDT

  • Interaction Between Main Thread and EDT

    • Initial GUI setup: Done on main thread, handed off to EDT via SwingUtilities.invokeLater

    • EDT Execution: Handles all GUI updates after initial setup

Layout Managers

  • Reminder: Setting layout manager to null results in absolute positioning (requires manually setting position/dimensions)

  • Common Layout Managers:

    • BorderLayout: Split into five regions (NORTH, SOUTH, EAST, WEST, CENTER)

      • Only one component per region, but nesting is possible

    • FlowLayout: Default layout; displays components inline

      • Accepts alignment parameters (LEFT, RIGHT, CENTER, etc.)

    • GridLayout: Displays components in a grid

      • One component per cell; nesting allows complex layouts

    • CardLayout: Manages views as a stack of cards

      • Only one component visible at a time, customizable via card names

    • BoxLayout: Displays components vertically or horizontally

      • Options: X_AXIS, Y_AXIS, LINE_AXIS, PAGE_AXIS

  • For a full list: https://www.javatpoint.com/java-layout-manager

  • Note: Layout managers are typically set on JFrame or JPanel

    • JFrame is the main window

    • JPanel groups subcomponents, allowing complex nested layouts

Getting Practical

Getting More Practical

  • UI Concept: Pseudo-chatroom (UI components with client-side simulation)

    • Added Username: Updates JFrame title based on username (handled in createUserInputScreen())

    • createChatScreen() Method: More complex layout with scroll pane

  • Panel Structure:

    • Parent Panel: Holds wrapper and content panels (servers as Card for CardLayout manager)

    • Wrapper Panel: Holds content panel within scroll pane

    • Content Panel: Holds chat items, uses BoxLayout for bottom alignment

  • Additional Details:

    • Input panel contains text input and send button

    • Input panel leverages a key listener so enter can send the message

  • When a message is sent:

    • Adds a message object to content panel, clears input text

    • Scrolls to the bottom for a normal chat log appearance

Getting More Practical Continued

  • Helper Methods:

    • addText(): Generates JEditorPane for text display, appends to content panel

      • Adjusts size, disables editing, applies styling

    • calcHeightForText(): Determines expected height for wrapped text

      • Calculates based on panel dimensions and font size

      • Far from perfect but it’s a short lived example

  • Code Example: PracticalUI2.java

One More Step

  • Improved UI:

    • Enhanced Layout: Replaced BoxLayout with GridBagLayout for better control

      • Messages start at the bottom, remain aligned as new messages are added

  • Updates:

    • Improved text handling to account for scrollbar width

    • Applied vertical glue to keep messages at the bottom

  • System Look and Feel:

    • Set look and feel via UIManager to match system’s default

  • Removed buggy calcHeightForText() function, enhanced alignment

  • Prepended username to messages for thoroughness

  • Code Example: PracticalUI3.java

Summary

  • Practice working with Java GUI, gain familiarity with UI building approaches

    • Modify layout managers to see how changes affect UI

  • Demoed Use of CardLayout:

    • Swap Panels like a deck of cards for modular views

  • Card Structure:

    • Each card has a parent Panel with one or more child panels for specific UI elements

    • Connection Screen:

      • Parent Panel

        • Content Panel with Host Info, Port Info, Next Button

    • Username Screen:

      • Parent Panel

      • Content Panel with Username Info, Next/Previous Buttons

    • Chat Screen:

      • Parent Panel

        • Wrapper Panel and Content Panel for messages, input panel for text and button

  • Full Module Link (Module 8 Folder): https://github.com/MattToegel/IT114/tree/M24-Java-UI