100% found this document useful (1 vote)
226 views41 pages

Swings: The Complete Reference To Java - Herbert Schild - Chapters 29 & 30

The document discusses Java Swing which provides platform-independent GUI components. It describes key Swing features like lightweight components and pluggable look and feel. It explains the model-view-controller architecture in Swing and compares AWT and Swing. It also covers common Swing components like JLabel and containers like JFrame.

Uploaded by

Aryan V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
226 views41 pages

Swings: The Complete Reference To Java - Herbert Schild - Chapters 29 & 30

The document discusses Java Swing which provides platform-independent GUI components. It describes key Swing features like lightweight components and pluggable look and feel. It explains the model-view-controller architecture in Swing and compares AWT and Swing. It also covers common Swing components like JLabel and containers like JFrame.

Uploaded by

Aryan V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Swings

THE COMPLETE REFERENCE TO JAVA – HERBERT SCHILD –


CHAPTERS 29 & 30
 JAVA provides a rich set of libraries to create Graphical
User Interface in a platform independent way.
 Java Swing  is a part of Java Foundation Classes (JFC)
that is used to create window-based applications . It is
built on the top of AWT (Abstract Windowing Toolkit)
API and entirely written in java.
 Unlike AWT, Java Swing provides platform-independent
and lightweight components.
 The javax.swing package provides classes for java
swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT & Swings
Sl.No AWT Swing
1 AWT components Java swing components are platform-
are platform-dependent. independent.
2 AWT components Swing components are lightweight
are heavyweight
3 AWT doesn't support Swing supports pluggable look and feel.
pluggable look and feel.
4 AWT provides less Swing provides more powerful
components than Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5 AWT doesn't follows Swing follows MVC
MVC(Model View Controller)
where model represents data,
view represents presentation
and controller acts as an
interface between model and
view.
Hierarchy of Java Swing classes
Two Key Swing Features

 Swing Components Are Lightweight


 Swing Supports a Pluggable Look and Feel
Two Key Swing Features

 Swing Components Are Lightweight


 Swing components arelightweight . This means that they are written
entirely in Java and do not map directly to platform-specific
peers.
 Because lightweight components are rendered using graphics
primitives, they can be transparent, which enables
nonrectangular shapes.
 Thus, lightweight components are more efficient and more
flexible.
 Furthermore, because lightweight components do not translate
into native peers, the look and feel of each component is
determined by Swing, not by the underlying operating system.
 This means that each component will work in a consistent
manner across all platforms.
 Swing Supports a Pluggable Look and Feel
 Swing supports apluggable look and feel (PLAF).
 Because each Swing component is rendered by Java code rather
than by native peers, the look and feel of a component is under
the control of Swing.
 This fact means that it is possible to separate the look and feel of
a component from the logic of the component, and this is what
Swing does.
 Separating out the look and feel provides a significant advantage:
it becomes possible to change the way that a component is
rendered without affecting any of its other aspects.
 In other words, it is possible to “plug in” a new look and feel for
any given component without creating any side effects in the
code that uses that component.
MVC Connection

 In general, a visual component is a composite of three distinct


aspects:
 The way that the component looks when rendered on the screen
 The way that the component reacts to the user
 The state information associated with the component
 themodel corresponds to the state information associated with
the component. For example, in the case of a check box, the
model contains a field that indicates if the box is checked or
unchecked.
 Theview determines how the component is displayed on the
screen, including any aspects of the view that are affected by the
current state of the model.
 Thecontroller determines how the component reacts to the user.
For example, when the user clicks a check box, the controller
reacts by changing the model to reflect the user’s choice
(checked or unchecked).
 By separating a component into a model, a view, and a controller,
the specific implementation of each can be changed without
affecting the other two.
 Swing uses a modified version of MVC that combines the view
and the controller into a single logical entity called theUI delegate .
 For this reason, Swing’s approach is called either theModel-
Delegate architecture or theSeparable Model architecture.
 To support the Model-Delegate architecture, most Swing
components contain two objects.
 The first represents the model.
 The second represents the UI delegate.
 Models are defined by interfaces. For example, the model for a
button is defined by the ButtonModel interface.
 UI delegates are classes that inherit ComponentUI. For example,
the UI delegate for a button is ButtonUI. Normally, your programs
will not interact directly with the UI delegate.
Components and Containers

 A Swing GUI consists of two key items:


 components and
 Containers
 Acomponent is an independent visual control, such as a push
button or slider.
 A container holds a group of components.
 Thus, a container is a special type of component that is designed
to hold other components.
 In order for a component to be displayed, it must be held within a
container.
 All Swing GUIs will have at least one container. Because
containers are components, a container can also hold other
containers.
 This enables Swing to definecontainment hierarchy , at the top of
which must be atop-level container .
Components

 Swing components are derived from the JComponent


class.
 JComponent provides the functionality that is common
to all components.
 For example, JComponent supports the pluggable look
and feel.
 JComponent inherits the AWT classes Container and
Component.
 A Swing component is built on and compatible with an
AWT component.
 All of Swing’s components are represented by classes
defined within the package
 javax.swing.
The following table shows the class names for
Swing components
Containers

 Swing defines two types of containers


 The first are top-level containers – Heavy weight Containers
 The second type of containers are lightweight containers
Containers

 The first are top-level containers:


 JFrame,
 JApplet,
 JWindow, and
 JDialog.

 These containers do not inherit JComponent.


 They inherit the AWT classes Component and Container.
 the top-level containers are heavyweight. This makes the top-level
containers a special case in the Swing component library.
 a top-level container must be at the top of a containment hierarchy.
 Atop-level container is not contained within any other container.
Furthermore, every containment hierarchy must begin with a top-level
container.
 The one most commonly used for applications is JFrame.
 The one used for applets is JApplet
 second type of containers supported by Swing are
lightweight containers.
 Lightweight containers do inherit JComponent.
 An example of a lightweight container is JPanel,
which is a general-purpose container.
 Lightweight containers are often used to organize
and manage groups of related components because
a lightweight container can be contained within
another container.
The Top-Level Container Panes

 Each top-level container defines a set ofpanes . At


the top of the hierarchy is an instance of JRootPane.
 JRootPane is a lightweight container whose purpose
is to manage the other panes.
 It also helps manage the optional menu bar.
 The panes that comprise the root pane are called
 theglass pane,
 thecontent pane, and
 thelayered pane.
Mandatory
• Component
• Layered
• Content

Optional
Glass pane

 The glass pane is the top-level pane.


 It sits above and completely covers all other panes.
 By default, it is a transparent instance of JPanel.
 The glass pane enables you to manage mouse
events that affect the entire container (rather than
an individual control) or to paint over any other
component, for example.
 In most cases, you won’t need to use the glass pane
directly, but it is there if you need it.
Layered pane

 The layered pane is an instance of JLayeredPane.


 The layered pane allows components to be given a
depth value.
 This value determines which component overlays
another.
 The layered pane holds the content pane and the
(optional) menu bar.
Content pane

 The pane with which your application will interact


the most is the content pane, because this is the
pane to which you will add visual components.
 In other words, when you add a component, such as
a button, to a top-level container, you will add it to
the content pane. By default, the content pane is an
opaque instance of JPanel.
The Swing Packages
JLabel and ImageIcon

 It creates a label
 JLabel can be used to display text and/or an icon.
 It is a passive component in that it does not respond to user input.
  JLabel defines several constructors.
 JLabel(Iconicon )
 JLabel(Stringstr )
 Jlabel(Stringstr , Iconicon , intalign )
Here, str  and icon  are the text and icon used for the label.
The align  argument specifies the horizontal alignment of the text and/or icon within
the dimensions of the label. It must be one of the following values:
 LEFT,
  RIGHT,
 CENTER, 
 LEADING, or
  TRAILING.
These constants are defined in theSwingConstants interface, along with several
others used by the Swing classes.
 The easiest way to obtain an icon is to use
the ImageIcon class.
  ImageIcon implements Icon and encapsulates an image.
 Thus, an object of type ImageIcon can be passed as
an argument to the Icon parameter of JLabel’s
constructor.
 There are several ways to provide the image, including
reading it from a file or downloading it from a URL.
 ImageIcon(String filename )
 It obtains the image in the file named filename .
 The icon and text associated with the label can be
obtained by the following methods:
 Icon getIcon( )
 String getText( )
 The icon and text associated with a label can be set
by these methods: 
 void setIcon(Icon icon )
 void setText(String str )
 
JTextField

 It is the simplest and widely used text component.


 JTextField allows you to edit one line of text.
 It is derived from JTextComponent, which provides the basic
functionality common to Swing text components.
 JTextField uses the Document interface for its model.
 Three of JTextField’s constructors are
 JTextField(intcols )
 JTextField(String str , intcols )
 JTextField(String str )
str is the string to be initially presented, andcols is the number of columns
in the text field.
If no string is specified, the text field is initially empty. If the number of
columns is not specified, the text field is sized to fit the specified string.
Java SWING JFrame Layouts Example

 Border Layout
 Flow Layout
 Grid Layout
Border Layout
 Border layout is one of the most common used layouts.
It is the default layout in JFrame. It can position
components in five different regions like top, bottom,
left, right and center. In border layout each region
contain only one component. All free space is placed in
the center.
 Use: Initialize content pane with border layout and add
components to it by add method and give layout as a
parameter.
Flow layout

 Flow layout is the common used layout. It is default


layout used by JPanel. It is used to arrange components
in a line or a row for example from left to right or from
right to left. It arranges components in a line, if no space
left remaining components goes to next line. Align
property determines alignment of the components as left,
right, center etc.
 Use: Set JFrame layout by using JFrame.
setLayout(layout), pass flow layout as a parameter.
Grid Layout

 Grid layout arranges component in rectangular grid.


It arranges component in cells and each cell has the
same size. Components are placed in columns and
rows. GridLayout(int rows, int columns) takes two
parameters that is column are row.
 Use: Set JFrame layout by using JFrame.
setLayout(layout), pass grid layout as a parameter.
 Following example shows components arranged in
grid layout (with 2 rows and 3 columns).
The Swing Buttons

 Swing defines four types of buttons:


 JButton,
 JToggleButton,
 JCheckBox, and
 JRadioButton.

 All are subclasses of the AbstractButton class,


which extends JComponent. Thus, all buttons share
a set of common traits.
 AbstractButton contains many methods that allow you to
control the behavior of buttons.
 For example, you can define different icons that are
displayed for the button when it is disabled, pressed, or
selected.
 Thers is another icon can be used as arollover icon,
which is displayed when the mouse is positioned over a
button.
 void setDisabledIcon(Icondi )
 void setPressedIcon(Iconpi )
 void setSelectedIcon(Iconsi )
 void setRolloverIcon(Iconri )
di, pi, si, and ri are the icons to be used for the indicated purpose
 The text associated with a button can be read and
written via the following methods
 String getText( )
 void setText(Stringstr )
str is the text to be associated with the button
 The model used by all buttons is defined by the
ButtonModel interface.
 A button generates an action event when it is
pressed.
JButton

 The JButton class provides the functionality of a


push button.
 JButton allows an icon, a string, or both to be
associated with the push button.
 Three of its constructors are shown here:
 JButton(Iconicon )
 JButton(Stringstr )
 Jbutton(Stringstr , Iconicon )
 When the button is pressed, an ActionEvent is generated.
Using the ActionEvent object passed to the
actionPerformed( ) method of the registered
ActionListener, you can obtain the action command
string associated with the button.
 By default, this is the string displayed inside the button.
However, you can set the action command by calling
setActionCommand( ) on the button.
 You can obtain the action command by calling
getActionCommand( ) on the event object.
 It is declared like this:
 String getActionCommand( )
JToggleButton

 A useful variation on the push button is called atoggle


button .
 A toggle button looks just like a push button, but it acts
differently because it has two states:
 pushed and
 released.
 When you press a toggle button, it stays pressed rather
than popping back up as a regular push button does.
When you press the toggle button a second time, it
releases (pops up).
 Therefore, each time a toggle button is pushed, it toggles
between its two states.
 Toggle buttons are objects of the JToggleButton class.
 JToggleButton implements AbstractButton.
 In addition to creating standard toggle buttons,
JToggleButton is a superclass for two other Swing
components that also represent two-state controls.These
are
 JCheckBox and
 JRadioButton,
 Thus, JToggleButton defines the basic functionality of
all two-state components.
 JToggleButton defines several constructors.
 JToggleButton(Stringstr )
This creates a toggle button that contains the text passed instr .
By default, the button is in the off position.
 JToggleButton generates an action event each time it
is pressed.
 JToggleButton also generates an item event. This
event is used by those components that support the
concept of selection.
 When a JToggleButton is pressed in, it is selected.
When it is popped out, it is deselected.
Check Boxes

 The JCheckBox class provides the functionality of a


check box.
 Its immediate superclass is JToggleButton, which
provides support for two-state buttons, as just
described.
 JCheckBox defines several constructors.
 JCheckBox(Stringstr )
It creates a check box that has the text specified bystr as a label
 When the user selects or deselects a check box, an
ItemEvent is generated.
 You can obtain a reference to the JCheckBox that
generated the event by calling getItem( ) on the
 ItemEvent passed to the itemStateChanged( )
method defined by ItemListener. The easiest way to
determine the selected state of a check box is to call
isSelected( ) on the JCheckBox instance.
Radio Buttons

 Radio buttons are a group of mutually exclusive buttons, in which


only one button can be selected at any one time.
 They are supported by the JRadioButton class, which extends
JToggleButton.
 JRadioButton provides several constructors.
 JRadioButton(Stringstr )
 radio buttons must be configured into a group.
 Only one of the buttons in the group can be selected at any time.
 For example, if a user presses a radio button that is in a group, any
previously selected button in that group is automatically
deselected. A button group is created by the ButtonGroup class.
 Its default constructor is invoked for this purpose. Elements are
then added to the button group via the following method:
 void add(AbstractButtonab )

You might also like