0% found this document useful (0 votes)
10 views

UI With Swing

Uploaded by

Khanal Gaurav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

UI With Swing

Uploaded by

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

SWING

AWT (Abstract Window Toolkit)


● The Abstract Window Toolkit (AWT) was Java’s first GUI framework, and it
has been part of Java since version 1.0.
● It contains numerous classes and methods that allow you to create windows
and simple controls.
● Java AWT is an API to develop GUI or window-based application in java.
● Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
● AWT is heavyweight i.e. its components uses the resources of system.
● The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Swing
● Not long after Java's original release, it became apparent that the limitations
and restrictions present in the AWT were sufficiently serious that a better
approach was needed.
● The solution was Swing.
● Introduced in 1997, Swing was included as part of the Java Foundation
Classes (JFC).
● Swing was initially available for use with Java 1.1 as a separate library.
● However, beginning with Java 1.2, Swing (and the rest of the JFC) was fully
integrated into Java
● Although Swing eliminates a number of the limitations inherent in the AWT,
Swing does not replace it.
● Instead, Swing is built on the foundation of the AWT.
● This is why the AWT is still a crucial part of Java.
● Swing also uses the same event handling mechanism as the AWT.
● Therefore, a basic understanding of the AWT and of event handling is
required to use Swing.
Swing Vs AWT
● Platform Independence:
○ AWT components are implemented using the native platform GUI toolkit, which means they may not
look and behave consistently across different platforms.
○ Swing, on the other hand, provides its own set of lightweight components that are consistent across all
platforms.
● Look and Feel:
○ AWT components rely on the native platform look and feel, which can lead to inconsistencies in
appearance and behavior.
○ Swing components have a pluggable look and feel architecture, allowing developers to choose a
specific look and feel for their application, or even create custom ones.
● Heavyweight Components:
○ AWT components are heavyweight, meaning they are directly tied to the native platform's resources.
This can lead to slower performance and reduced flexibility.
○ Swing, in contrast, provides lightweight components that are rendered entirely in Java, resulting in
improved performance and greater flexibility.
● Better Layout Managers:
○ Swing includes additional layout managers that provide more control over the arrangement
and sizing of components, making it easier to create complex and responsive user interfaces.
● Lack of Advanced Components:
○ AWT lacks several advanced GUI components that are commonly used in modern
applications, such as tables, trees, and tabbed panes.
○ Swing includes a rich set of such components, making it easier to create complex user
interfaces.
Java Applet
● An applet is a Java program that runs inside the web browser and works at
client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
● Applets are used to make the website more dynamic and entertaining.
● Execution of an applet does not begin at main() method.
● Types of Applet:
○ Applet
○ JApplet
Running with Html
1. <html>
2. <body>
3. <applet code="FirstApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Running with applet viewer
GUI Controls
● JTextField
● JTextArea
● JPassword
● JScrollPane
● JLabel
● JCheckBox
● JRadioButton
Applet Life cycle
● init
○ This method is intended for whatever initialization is needed for your applet.
○ It is called only once in a program
● start
○ This method is automatically called after the browser calls the init method.
○ It is also called whenever the user returns to the page containing the applet after having gone
off to other pages.
● paint
○ Invoked immediately after the start() method, and also any time the applet needs to repaint
itself in the browser.
○ The paint() method is actually inherited from the java.awt.
● stop
○ This method is automatically called when the user moves off the page on which the applet sits.
○ It can, therefore, be called repeatedly in the same applet.
● destroy
○ This method is only called when the browser shuts down.
Swing Hierarchy
Component
● At the top of the AWT hierarchy is the Component class.
● Component is an abstract class that encapsulates all of the attributes of a
visual component.
● Except for menus, all user interface elements that are displayed on the screen
and that interact with the user are subclasses of Component.
● It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the
window, and repainting.
● A Component object is responsible for remembering the current foreground
and background colors and the currently selected text font.
Container
● The Container class is a subclass of Component.
● It has additional methods that allow other Component objects to be nested
within it.
● The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc.
● The classes that extends Container class are known as container such as
JFrame, JDialog and JPanel.
● A container is responsible for laying out (that is, positioning) any components
that it contains
JLabel
● JLabel is Swing’s easiest-to-use component.
● JLabel can be used to display text and/or an icon.
● It is a passive component that it does not respond to user input.
● JLabel defines several constructors. Here are three of them:
○ JLabel(Icon icon)
○ JLabel(String str)
○ JLabel(String str, Icon icon, int align)
● 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.
JTextField

● JTextField is the simplest Swing text component.


● It is also probably its most widely used text component.
● JTextField allows you to edit one line of text.
● Three of JTextField constructors are shown here:
○ JTextField(int cols)
○ JTextField(String str, int cols)
○ JTextField(String str)
● Here, str is the string to be initially presented, and cols 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 JTextArea

● The object of a JTextArea class is a multi line region that displays text.
● It allows the editing of multiple line text.
● Commonly used constructor are:
○ JTextArea()
○ JTextArea(String s)
○ JTextArea(int row, int column)
○ JTextArea(String s, int row, int column)
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(Icon icon)
○ JButton(String str)
○ JButton(String str, Icon icon)
● Here, str and icon are the string and icon used for the button.
● When the button is pressed, an ActionEvent is generated.
JPasswordField
● The object of a JPasswordField class is a text component specialized for
password entry.
● It allows the editing of a single line of text.
● It inherits JTextField class.
● Common Constructors are:
○ JPasswordField()
○ JPasswordField(String str)
○ JPasswordField(int column)
○ JPasswordField(String str, int column)
Check Boxes
● The JCheckBox class provides the functionality of a check box.
● JCheckBox defines several constructors.
○ JCheckBox(String str)
○ JCheckBox(String text, boolean selected)
○ JCheckBox()
● When the user selects or deselect a checkbox, an ItemEvent is generated.
● 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.
● JRadioButton provides several constructors.
○ JRadioButton(String str)
● Here, str is the label for the button. Other constructors let you specify the
initial selection state of the button and specify an icon.
● In order for their mutually exclusive nature to be activated, radio buttons must
be configured into a group.
● Only one of the buttons in the group can be selected at any time.
● A button group is created by the ButtonGroup class.
● A a reference to the button to be added to the group.
JComboBox
● Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class.
● A combo box normally displays one entry, but it will also display a drop-down list that
allows a user to select a different entry.
● You can also create a combo box that lets the user enter a selection into the text field.
● In the past, the items in a JComboBox were represented as Object references.
However, beginning with JDK 7, JComboBox was made generic and is now declared
like this: class JComboBox<E>
● Here, E represents the type of the items in the combo box.
● The JComboBox constructor:
○ JComboBox(E[ ] items)
○ JComboBox()
● Here, items is an array that initializes the combo box.
Slider
● The Java JSlider class is used to create the slider.
● By using JSlider, a user can select a value from a specific range.
● Constructor:
○ JSlider()
○ JSlider(int orientation)
○ JSlider(int min, int max)
○ JSlider(int min, int max, int value)
○ JSlider(int orientation, int min, int max, int value)

Orientation are: JSlider.HORIZONTAL or JSlider.VERTICAL


Layout manager
● Layout means the arrangement of components within the container.
● In other way we can say that placing the components at a particular
position within the container.
● The task of layouting the controls is done automatically by the Layout
Manager.
● A layout manager automatically arranges your controls within a window by using some
type of algorithm.
● Each Container object has a layout manager associated with it.
● The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made,
then the default layout manager is used.
● Whenever a container is resized (or sized for the first time), the layout manager is used
to position each of the components within it.
● The setLayout( ) method has the following general form:
○ void setLayout(LayoutManager layoutObj)
● Here, layoutObj is a reference to the desired layout manager.
● If you wish to disable the layout manager and position components manually,
pass null for layoutObj
● If you do this, you will need to determine the shape and position of each
component manually, using the setBounds( ) method defined by Component.
Flow Layout
● FlowLayout is the default layout manager.
● FlowLayout implements a simple layout style, which is similar to how words flow in
a text editor.
● The direction of the layout is governed by the container’s component orientation
property, which, by default, is left to right, top to bottom.
● Therefore, by default, components are laid out line-by-line beginning at the upper-
left corner. In all cases, when a line is filled, layout advances to the next line.
● A small space is left between each component, above and below, as well as left
and right. Here are the constructors for FlowLayout:
○ FlowLayout( )
○ FlowLayout(int align)
○ FlowLayout(int align, int hgap, int vgap)
● The first form creates the default layout, which centers components and leaves
five pixels of space between each component.
● The second form lets you specify how each line is aligned. Valid values for how
are as follows:
○ FlowLayout.LEFT
○ FlowLayout.CENTER
○ FlowLayout.RIGHT
○ FlowLayout.LEADING
○ FlowLayout.TRAILING
● These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
● The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
BorderLayout
● The BorderLayout class implements a common layout style for top-level
windows.
● It has four narrow, fixed-width components at the edges and one large area in
the center.
● The four sides are referred to as north, south, east, and west. The middle area
is called the center.
● Here are the constructors defined by BorderLayout:
○ BorderLayout( )
○ BorderLayout(int horz, int vert)
● The first form creates a default border layout.
● The second allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.
● BorderLayout defines the following constants that specify the regions:
○ BorderLayout.CENTER
○ BorderLayout.EAST
○ BorderLayout.WEST
○ BorderLayout.NORTH
○ BorderLayout.SOUTH
● When adding components, you will use these constants with the following
form of add( ), which is defined by Container:
○ void add(Component compRef, Object region)
● Here, compRef is a reference to the component to be added, and region
specifies where the component will be added.
Grid Layout
● GridLayout lays out components in a two-dimensional grid.
● When you instantiate a GridLayout, you define the number of rows and columns.
● The constructors supported by GridLayout are shown here:
○ GridLayout( )
○ GridLayout(int numRows, int numColumns)
○ GridLayout(int numRows, int numColumns, int horz, int vert)
● The first form creates a single-column grid layout.
● The second form creates a grid layout with the specified number of rows and columns.
● The third form allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.
● Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimited-length columns. Specifying numColumns as zero allows for unlimited-length
rows.
GridBagLayout
● We can specify the relative placement of components by specifying their positions within
cells inside a grid.
● The key to the grid bag is that each component can be a different size, and each row in
the grid can have a different number of columns. This is why the layout is called a grid
bag. It’s a collection of small grids joined together.
● The location and size of each component in a grid bag are determined by a set of
constraints linked to it. The constraints are contained in an object of type
GridBagConstraints. Constraints include the height and width of a cell, and the placement
of a component, its alignment, and its anchor point within the cell.
● The general procedure for using a grid bag is to first create a new GridBagLayout object
and to make it the current layout manager.
● Then, set the constraints that apply to each component that will be added to the grid bag.
● Finally, add the components to the layout manager.
Constraints
● gridx, gridy
○ Specify the row and column at the upper left of the component. The leftmost column has
address gridx=0 and the top row has address gridy=0.
● gridwidth, gridheight
○ Specify the number of columns (for gridwidth) or rows (for gridheight) in the
component's display area. These constraints specify the number of cells the component
uses, not the number of pixels it uses. The default value is 1.
● ipadx, ipady
○ Specifies the internal padding: how much to add to the size of the component. The
default value is zero.
● fill
○ This field is used when the component's display area is larger than the component's
requested size. It determines whether to resize the component, and if so, how.
○ The following values are valid for fill:
■ NONE: Do not resize the component.
■ HORIZONTAL: Make the component wide enough to fill its display area horizontally, but
do not change its height.
■ VERTICAL: Make the component tall enough to fill its display area vertically, but do not
change its width.
■ BOTH: Make the component fill its display area entirely.
GroupLayout

● GroupLayout groups its components and places them in a Container


hierarchically. The grouping is done by instances of the Group class.
● Group is an abstract class, and two concrete classes which implement this
Group class are SequentialGroup and ParallelGroup.
● SequentialGroup positions its child sequentially one after another whereas
ParallelGroup aligns its child on top of each other.
● The GroupLayout class provides methods such as createParallelGroup() and
createSequentialGroup() to create groups.
● GroupLayout treats each axis independently. That is, there is a group
representing the horizontal axis, and a group representing the vertical axis.
● Each component must exist in both a horizontal and vertical group.
Menu
● A top-level window can have a menu bar associated with it.
● A menu bar displays a list of top-level menu choices. Each choice is associated with a
drop-down menu.
● This concept is implemented in the Swing by the following classes: JMenuBar, JMenu,
and JMenuItem.
● In general, a menu bar contains one or more Menu objects. Each Menu object contains
a list of MenuItem objects. Each MenuItem object represents something that can be
selected by the user.
● Since JMenu is a subclass of JMenuItem, a hierarchy of nested submenus can be
created. It is also possible to include checkable menu items. These are menu options of
type JCheckboxMenuItem and will have a check mark next to them when they are
selected.
Steps to Create Menu
● Create menu bar
● Add menu bar to the frame
● Create menus
● Add menus to menu bar
● Create menu items
● Add menu items to menus
● Event handling(If required)
1. Create MenuBar

To create a menu bar, first create an instance of MenuBar. This class defines only
the default constructor.
● JMenuBar()
2. Create menu
Following are the constructors for Menu:
● JMenu( ) throws HeadlessException
● JMenu(String optionName) throws HeadlessException
● JMenu(String optionName, boolean removable) throws HeadlessException
● Here, optionName specifies the name of the menu selection. If removable is
true, the menu can be removed and allowed to float free. Otherwise, it will
remain attached to the menu bar. (Removable menus are implementation-
dependent.)
● The first form creates an empty menu.
3. Create Menu Item
● Individual menu items are of type MenuItem.
● It defines these constructors:
○ JMenuItem( )
○ MenuItem(String itemName)
○ MenuItem(String itemName, int memonic)
● You can disable or enable a menu item by using the setEnabled( ) method. Its form is shown here:
○ void setEnabled(boolean enabledFlag)
○ If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is
disabled.
Dailog Box
● Often, you will want to use a dialog box to hold a set of related controls.
● Dialog boxes are primarily used to obtain user input and are often child windows of a top-level
window.
● Dialog boxes don’t have menu bars, but in other respects, they function like frame windows. (You
can add controls to them, for example, in the same way that you add controls to a frame window.)
● Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed
to it until it is closed. This means that you cannot access other parts of your program until you
have closed the dialog box.
● When a modeless dialog box is active, input focus can be directed to another window in your
program. Thus, other parts of your program remain active and accessible.
● In the Swing, dialog boxes are of type Dialog. Two commonly used constructors are shown here:
● JDialog(Frame parentWindow, boolean mode)
● JDialog(Frame parentWindow, String title, boolean mode)
● Here, parentWindow is the owner of the dialog box. If mode is true, the dialog
box is modal. Otherwise, it is modeless. The title of the dialog box can be
passed in title. Generally, you will subclass Dialog, adding the functionality
required by your application.
FileDialog
● Java provides a built-in dialog box that lets the user specify a file.
● To create a file dialog box, instantiate an object of type JFileChooser. This
causes a file dialog box to be displayed.
● Usually, this is the standard file dialog box provided by the operating system.
Here are three FileDialog constructors:
○ JFileChooser()
○ JFileChooser(String currentDirectory)
● FileDialog provides methods that allow you to determine the name of the file
and its path as selected by the user. Here are two examples:
○ String getDirectory( )
○ String getFile( )
● These methods return the directory and the filename, respectively.
Tooltip
● Tooltips are small windows of text that popup when the user leaves the mouse
cursor over a component.
● They are used to explain the functionality of the component.
● Tooltips are an integral part of Swing components. They can be specified by
calling the setToolTipText method as shown below.
○ setToolTipText("Deletes the selected grocery item");
JcolorChooser
● JColorChooser provides a pane of controls designed to allow a user to
manipulate and select a color.
● Constructors:
○ JColorChooser(): Creates a color chooser pane with an initial color of white.
○ JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.
Internal Frame
● JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many
features of a frame which includes displaying title, opening, closing, resizing, support for menu
bar, etc.
● Constructors for JInternalFrame
○ JInternalFrame() : creates a new non- closable, non- resizable, non- maximizable JInternalFrame with no title
○ JInternalFrame(String t) :creates a new non- closable, non- resizable, non- maximizable JInternalFrame with a
title specified
○ JInternalFrame(String t, boolean resizable) :creates a new non- closable, non- maximizable JInternalFrame with a
title and resizability specified
○ JInternalFrame(String t, boolean resizable, boolean closable) : creates a new non- maximizable JInternalFrame
with a title, closability and resizability specified
○ JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable) :creates a new
JInternalFrame with a title, closability, maximizability and resizability specified
○ JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable : creates a new
JInternalFrame with a title, closability, maximizability, and resizability specified
Table
● The JTable class is a part of Java Swing Package and is generally used to
display or edit two-dimensional data that is having both rows and columns. It
is similar to a spreadsheet. This arranges data in a tabular form.
● Constructors in JTable:
○ JTable(): A table is created with empty cells.
○ JTable(int rows, int cols): Creates a table of size rows * cols.
○ JTable(Object[][] data, Object []Column): A table is created with the specified name where
[]Column defines the column names.
Tree
● The JTree class is used to display the tree structured data or hierarchical
data.
● JTree is a complex component.
● It has a 'root node' at the top most which is a parent for all nodes in the tree.
● Constructors:
○ JTree()
○ JTree(Object[] value)
○ JTree(TreeNode root)

You might also like