0 ratings 0% found this document useful (0 votes) 24 views 33 pages Swing
Swing is a Java framework for creating lightweight, platform-independent graphical user interfaces (GUIs) using components like buttons, text fields, and menus. It follows a loosely based Model-View-Controller (MVC) architecture and supports various events and event listeners for user interactions. Swing also includes a range of components such as tables and trees for structured data representation, as well as layout managers for organizing GUI elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
SWINGIntroduction to Swing
© Swing in java is part of Java foundation class which
is lightweight and platform independent.
~ |tis used for creating window based Sl annette ie
includes components like button, scroll bar, text
field etc.
~ The javax.swing package provides classes for java
swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser
etc. Putting together all these components makes a
graphical user interface
_ It is build on top of the AWT API and entirely written
peeveOF
©
6
i)
MVC Architecture
Swing API architecture follows loosely based MVC
architecture in the following manner.
Model represents component's data.
View represents visual representation of the
component's data.
Controller takes the input from the user on the view
and reflects the changes in Component's data.
Swing component has Model as a seperate
element, while the View and Controller part are
clubbed in the User Interface elements. Because of
which, Swing has a pluggable look-and-feel
architecture.WNodel-“View-Controller Architecture Block Diagram
— HTTP Request
Interaction
the DatabaseSwing Events
© Events are generated as a result of user
interaction with the graphical user interface
components.
~ For example, clicking on a button, moving
the mouse, entering a character through
keyboard, selecting an item from the list, and
scrolling the page are the activities that
causes an event to occur.Types of Swing Events
. Action Events: These events are triggered by user
actions like button clicks and menu selections. They are
typically used to perform specific tasks or actions.
~ Mouse Events: These events are triggered by mouse
actions such as clicks, movements, and drags. They are
useful for creating interactive graphics and handling
mouse-based interactions.
_ Key Events: Key events are generated when the user
interacts with the keyboard. You can capture and respond
to keystrokes like key presses and releases.
Window Events: Window events are associated with the
JFrame and include actions like opening, closing, resizing,
Flare] Waa window. These events are important for
managing the application's user interface.Event Listeners and Handling
© Event Listeners: In Swing, event listeners are
responsible for monitoring specific components
and reacting to events. Common event listener
interfaces include ActionListener,
MouseListener, and KeyListener.
~ Registering Event Listeners: To handle
events, you need to register listeners with the
components that generate events. For example,
to handle a button click, you would register an
PeNed(e)g] Mclaren an a= OU] Ace] aRSwing Adapters
© Swing Adapters are classes provided by
Swing to simplify event listener
implementation.
~ They act as intermediary classes that
provide default implementations for various
listener interfaces, allowing developers to
override only the specific methods they
need.Types of Swing Adapters
» Adapter Classes: Swing provides adapter classes for
various listener interfaces. Some common adapter classes
include:
MouseAdapter: Provides default implementations for mouse-
related events (e.g., mouseClicked, mousePressed).
KeyAdapter: Offers default implementations for keyboard-
related events (e.g., keyPressed, keyReleased).
WindowAdapter: Simplifies window-related events (e.g.,
windowOpened, windowClosing).
FocusAdapter: Deals with focus-related events (¢.9.,
focusGained, focusLost).
_ Custom Adapter Classes: Developers can also create
their custom adapter classes by extending the adapter
classes provided by Swing and overriding specific
methods as needed.import javax.swing.";
import java.awt.event.MouseAdapter;
nee eR aercua oes nts
piaias eorstigh Cecrs eur aet
public static void main(String[] args) {
Meena eee acces iehce iCal hisewh
JButton button = new JButton("Click Me");
Peet el ec eS earen Geta nec eT CH Nn
@Override
eae mule ented
Nelsen en ieee et 12). 1sI iret TnCeumel os
y
M
BCI LCL sco aeText Components in Swing:
© Swing provides a variety of text components
that allow you to work with text, both for
displaying and editing purposes.Common Swing Text
Components
JTextField - Single-Line Text Input
JTextField: This component is used for single-line text input fields.
It's ideal for short text input, such as usernames and search queries.
BMC ETN WC gmoney sere m ome cm uel
JTextArea - Multi-Line Text Input
Sed ter Cameleon aa Rn oma E ae Cosa ast g
and display.
It's suitable for text fields that may contain paragraphs or longer descriptions.
You can control scrolling and set word wrap preferences,
JTextPane and JEditorPane - Rich Text Editing
JTextPane and JEditorPane; These components support rich text
formatting, including bold, italics, underline, and the display of inline
images.
JTextPane is designed for plain text with farmatting.
RTSoll elise ute cure a aM eee Cla MLL (elLM os AR CLAimport javax.swing.*;
import java.awt.*;
public class SwingTextComponentExample {
‘public static void main(Stringl] args) {
eer dea oI Hees ae Text jg
Pte Ma Ss raSwing components
© Swing components are the building blocks of
graphical user interfaces (GUIs) in Java.
They provide a variety of widgets, such as
buttons, text fields, labels, menus, and
tables, that can be used to create rich and
interactive interfaces.Swing components-Look and
feel
© Swing components are all subclasses of the
JComponent class, which provides a
common set of methods and properties for
all Swing components. For example, all
Swing components can be resized, moved,
and added to other Swing components.Swing component classes
ax. swing. JComponent
avex. swing. JContainer
jovox .swing. JDialog
javax. swing. JFrame
jovox.swing. JPanel
jovax. swing. JRootPane
jovax . swing. JViewportCommon Swing Components
JFrame; JFrame is the top-level container for a Swing application, serving as the
RETARCin clot a Coantretige sialic tien
Re BE la elaMRC Me A Nuiel(°] a) Reels tela shel Lce) eRe Lae Me lte Ec LurscMe Lol
components, providing layout flexibility.
JButton: JButton is a basic button component that responds to user clicks.
JLabel: JLabel is used for displaying non-editable text or images.
Myo deat) (eMedia cle Mee el esl ath anole LMU Ime ELL
JTextArea: JTextArea is a multi-line text input and display area.
le ere tT UTC Cel -Tehs tel Baa SL aes Sete Cir ieee st CLM LL)
ere mera WIRE ee) Gelea
JComboBox: JComboBox is a drop-down list or combo box for selecting items
Licence
B= te Colom) folie (eno leitnca olestolls(elee=mYEelITM CLUE MIae(=m os MLN ee 0,1
JTable: JTable is used to display and edit tabular data.
JFileChooser: JFileChooser provides a dialog for selecting files and directories.import javax.swing.";
import java.awt.*;
public class SwingComponentsExample {
public static void main(String] args) {
JFrame frame = new JFrame("Swing Components Example");
Bi oreTaledMec=LtT= Nem SIAR az-TA=)| OH
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, Swing!");
panel.add(label);
panel.add(buttor
frame.add(pane!Containers and Frames
© Understanding Containers: In graphical user
interface (GUI) programming, containers are
essential components that hold and organize
other graphical elements, such as buttons,
labels, and text fields. Containers provide
structure and layout for GUI components.
~ The Role of Frames: A frame is a top-level
container in Swing. It represents the main
window of a GUI application. Frames serve as
the outermost structure for organizing and
displaying various components.®
Types of Containers
JFrame: The JFrame class is used to create the main
application window. It is a top-level container that typically
contains all other GUI components. You can set attributes
such as the window's title, size, and close operation.
JPanel: The JPanel class is a lightweight container that
can be used within a JFrame or other containers. It is often
used to group related components and provides layout
flexibility.
Content Pane: The content pane is a container that
resides within the JFrame. It is where most GUI
components are add ed. The content pane allows you
to arrange components using layout managers.Frames and Containers in
Swing Applications
. Creating a Frame: To create a frame, you instantiate a
JFrame object, set its attributes, and add components to it.
Deac(s [late Mere) ile) y peer emal Saal method to add
components like buttons, labels, and text fields to
containers, such as the content pane of a JFrame.
Layout Managers: Layout managers are used to control
the arrangement and positioning of components within
containers. Common layout managers include FlowLayout,
BorderLayout, and GridLayout.
_ Event Handling: Implement event listeners to make the
GUI components interactive. For instance, use an
ActionListener to handle button clicks.import javax.swing.*;
import java.awt.*;
public class SwingContainerExample {
public static void main(String{] args) {
JFrame frame = new JFrame("Swing Container Example");
JPanel panel = new JPanel();
JButton button = new JButton("Glick Me");
JLabel label = new JLabel("Hello, Swing!");
panel.add(label):
panel.add(button);
1)Swing menus and toolbars
© Swing tables and trees are essential
components in Java for creating structured,
data-rich graphical user interfaces (GUIs).
Tables are used for displaying data in rows
and columns, while trees are employed for
hierarchical data representation.Tables and Trees
© JTable: JTable is a Swing component for
displaying tabular data in a grid format. It's
ideal for structured and spreadsheet-like
data presentation.
~ JTree: JTree, on the other hand, is used to
display hierarchical data, such as file
systems, organization charts, or nested
categories.Creating JTables
» Creating a Basic JTable: You can create a simple
JTable by instantiating the JTable class and
providing it with a TableModel to define the data
Stave leo
TableModel: The TableModel interface is
responsible for managing and retrieving the data to
be displayed in the JTable. You can use default
implementations like DefaultTableModel or create
custom models.
_ Customizing JTable: You can customize JTables
by defining custom cell renderers and editors to
format and handle cell contents.
©import java.awt.FlowLayout;
(Ti sfolng NVR a cialolm-hi7ol8
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
Cullen e EN eh eines ecu oe
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;public SwingTester(){
prepareGUI();
}
public static void main(String[] args){
SwingTester swingControlIDemo = new SwingTester();
Rimes arene ECP OH
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame-setSize(500,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
i
be
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel(" JLabel. CENTER);
Fae Use ter- ere sir eis a O10)ferelaN Cs) ae-ae eeMltL he L1N0
contro!Panel.setLayout(new FlowLayout());
mainFrame.add(headerl abel);
mainFrame.add(controlPanel);
Ree cele y
GULL ect,
ee
private void showTableDemo(){’
headerLabel.setText("Contro! in action: JTable");
String) columnNames = {"Name", "Salary"},Java Swing Examples
Controtin sete: JTable.
ame,
‘Ramesh Raman
Shab HusseinCreating JTrees
© Creating a Basic JTree: JTrees require a
TreeModel to define the structure. You can
create a simple JTree by setting up a
DefaultTreeModel.
~ TreeNode: JTree nodes are represented by
the TreeNode interface, allowing for a
flexible hierarchical structure.
_ Customizing JTree: You can customize
JTrees by creating custom cell renderers,
editors, and custom icons for nodes.© We are using the following APIs.
© JTree(root) — To create a tree.
~ DefaultMutableTreeNode() - To create a
tree node.
~ DefaultMutableTreeNode().add(node) - To
add a tree node to a tree node.