swing I -
Introduction to Swing
Java AWT: Original Java package for creating GUIs (Graphical User Interfaces).
Swing Package: Improved version of AWT; it does not completely replace AWT, some AWT classes are still necessary.
Event-Driven Programming: Swing GUIs use this object-oriented programming approach.
/
Events
Event-Driven Programming: A programming style based on a signal-and-response method.
Event: An object signaling another object (listener). Example: A button click fires an event.
Listeners
Listener Object: Performs actions in response to events; multiple listeners can respond to the same or different events.
Exception Objects
Exception: Acts as an event; throwing an exception fires the event. The catch block acts as the listener.
Event Handlers
Event Handlers: Methods in listener objects that define actions for different kinds of events.
Event-Driven Programming
Unlike typical programming (sequential statements), event-driven programming reacts to events, determining the order of execution.
Methods may be invoked automatically upon the occurrence of events, rather than explicitly in code.
JFrame Object
JFrame: Main window object; includes controls for minimizing, resizing, and closing.
Example:
JFrame firstWindow = new JFrame();Components like buttons and labels can be added to JFrame using
add()method.
Action Listeners and Events
Firing Events: Button clicks trigger action events, sent to listener objects.
ActionListener: Interface that must be implemented to handle action events through the method
actionPerformed(ActionEvent e).
Tips for Programming in Swing
To end a GUI program, use
System.exit(0)when the user indicates to close the application.Event Handling: Ensure that the actionPerformed method follows the specified header rules in ActionListener interface.
Layout Managers
Purpose: Control the arrangement of components in a container.
Types of Layout Managers:
BorderLayout: Divides the frame into five regions (NORTH, SOUTH, EAST, WEST, CENTER).
FlowLayout: Arranges components in a row, wrapping them as necessary.
GridLayout: Arranges components in a grid of rows and columns, where each component fills its space.