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

Adavanced Java 1

Advanced java contents for msbte syllabus.

Uploaded by

San Nitro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Adavanced Java 1

Advanced java contents for msbte syllabus.

Uploaded by

San Nitro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

Advanced Java Programming

(AJP-22517)

AKUDE P.A.
Chapter 1&2
Introduction to Abstract
Windowing Toolkit(AWT) & Swing

15/03/2024 Akude P.A. 4


Introduction to Abstract Windowing
Toolkit(AWT) & Swing
• Objectives

To design & develop Graphical
 user interface (GUI) programs using
 AWT and swing component.

To arrangethe GUI components using different layout
managers.

15/03/2024 Akude P.A. 5


CONTENTS
• Component, container, window, frame, panel.
• Creating windowed programs & applets.
• AWT controls & layout managers
Understanding the use of AWT controls: labels, buttons, checkbox,
checkbox group, scroll bars, text field, text area, Understanding the
use of layout managers: flow Layout, border Layout, grid Layout,
cardLayout, gridbagLayout,menubars, menus, dialog boxes, file dialog.
• Introduction to swing
Swing features, MVC Architecture, Combo Boxes, progress
bar, tool tips, seperator, tables, trees, toggle button.

15/03/2024 Akude P.A. 6


15/03/2024 Akude P.A. 7
GUI (Graphical User Interface)
• GUI offers user interaction via some
graphical components.
• Window, frame, Panel, Button, Textfield,
TextArea, Listbox, Combobox, Label,
Checkbox etc.
• Using these components we can create an
interactive user interface for an application.
• GUI provides result to end user in response
to raised event.
• GUI is entirely based event.

15/03/2024 Akude P.A. 8


AWT (Abstract Window Toolkit)
• AWT contains numerous classes and methods that allow
you to create and manage window.
• import java.awt.*;
• 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.

15/03/2024 Akude P.A. 9


AWT Class Hierarchy

15/03/2024 Akude P.A. 10


AWT Class Hierarchy

15/03/2024 Akude P.A. 11


15/03/2024 Akude P.A. 12
Component

• Component is an object having a graphical


representation that can be displayed on the
screen and that can interact with the user.
• At the top of the AWT hierarchy is
the Component class.
• It is abstract class that encapsulates all of
the attributes of a visual 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.
15/03/2024 Akude P.A. 13
15/03/2024 Akude P.A. 14
Container

• Container class is a subclass of Component.


• Provided additional methods that allow
other Component to place on it.
• It does this through the use of various
layout managers.
• Container is a component in AWT that can
contain another components like buttons,
text fields, labels etc.
• The classes that extends Container class are
known as container such as Frame, Dialog
and Panel.
15/03/2024 Akude P.A. 15
Containers and Components

• The job of a Container is to hold and


display Components
• Some common subclasses of Component are
Button, Checkbox, Label, Scrollbar,
TextField, and TextArea
• A Container is also a Component
• Some Container subclasses are Panel (and
Applet, JApplet), Window (Frame, JFrame)

15/03/2024 Akude P.A. 16


Panel

• Panel is one type of container that does not


contain a title bar, menu bar, or border.
• When you run an applet using an applet
viewer, the applet viewer provides the
title and border.
• Uses add() to add component defined
by container.
• Uses setSize(), setLocation(),
setBounds() defined by Component.
15/03/2024 Akude P.A. 17
AWT Controls:

• Component which allows you to interact with application.


• Labels
• Button
• Checkbox
• Checkbox group
• Scrollbars
• Text field
• Text Area
• Lists
• Choice lists
etc

15/03/2024 Akude P.A. 18


AWT Controls:
• Controls are components that allows user
to interact with application.
•Adding the control in Window
  
First create instance of desired control.
 
Then add it to window by calling add() method

•Removing the Control


  
Call remove() method defined by container

removeAll()method to remove all controls defined by
container.

15/03/2024 Akude P.A. 19


Labels
• Used to just display string on window.
• Passive Components
• Constructors:
Label( )
Label(String str) //left - justified
Label(String str, int how) // Label.LEFT, Label.RIGHT,
Label.CENTER ex:
Label label_name;
label_name =new Label(“”);
add(label_name);
• Methods to perform
operation About text:
• void setText(String str)
• String getText( )
• About Alighment
• void setAlignment(int how)
• int getAlignment( )

15/03/2024 Akude P.A. 20


import java.awt.*;

public class LabelExample {


public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Button
• It contains a label and that generates an event when
it is pressed.
• Active Components
• Constructors:
– Button( )
– Button(String str)
ex:
Button btn_name;
btn_name =new Button(“”);
add(btn_name);

• Methods to perform operation: Setter and


Getter Method.
– void setLabel(String str)
– String getLabel( )

15/03/2024 Akude P.A. 21


import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Awt Control:TextField
• Using a TextField The TextField class implements a single-line
text-entry area, usually called an edit control.
• Text fields allow the user to enter strings and to edit the text
using the arrow keys, cut and paste keys, and mouse selections. It
is subclass of TextComponent.
• TextField defines the following constructors:
  
TextField( ) - The first version creates a default text field

TextField(int numChars)
 - The second form creates a text field that is numChars
 characters wide

TextField(Stringstr) - The third form initializes the text field with the string
 contained in str

TextField(String
 str, int numChars)- The fourth form initializes a text field and
sets its width
• It provides several methods that allow you to utilize a text field.
  
getText( ):- To obtain the string currently contained in the text field.
 
setText(String str ):- To set the text.

15/03/2024 Akude P.A. 26


TextArea
• AWT includes a simple multiline editor called TextArea.
• Following are the constructor for TextArea:
  
TextArea( )
  
TextArea(int numLines, int numChars)
  
TextArea(String str)
  
TextArea(String str, int numLines, int numChars)
  
TextArea(String str, int numLines, int numChars, int sBars)
Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str.
/importing AWT class
import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to javatpoint");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}

AWT Layout Managers

A layout refers
 to arranging and placing the components in a container this is same like arranging the furniture
 in a house.

 For his purpose Java has Layout Manager Interface which is used for Placing the Components in the Container
like Applet or in the Panel etc.
 
 All of the components that we have shown so far have been positioned by the default layout manager
 
 Each Container object has a layout manager associated with it.
 
 A layout manager is an instance of any class that implements the LayoutManager interface.
 
 The layout manager is set by the setLayout( ) method.
 
 If no call to setLayout( ) is made, then the default layout manager is used.
 
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.
 
 Normally, you will want to use a layout manager.
 
 Each layout manager keeps track of a list of components that are stored by their names.
 
 Whenever the container needs to be resized, the layout manager is consulted via its
 
 minimumLayoutSize( )and preferredLayoutSize( ) methods.

Each component that is being managed by a layout manager contains the getPreferredSize( ) and
getMinimumSize(
 ) methods. These return the preferred and minimum size required to display each
component.

15/03/2024 Akude P.A. 32


Layout Managers
• FlowLayout
• BorderLayout
• GridLayout
• CardLayout
• GridBagLayout

15/03/2024 Akude P.A. 33


Different Layout Manager
 
FlowLayout
The FlowLayout is the default layout.It the components in
a directional/horizontally flow.
 
BorderLayout
The borderlayout arranges the components to fit in the five regions:
east, west, north, south and center.
 
GridLayout
The GridLayout manages the components in form of a rectangular grid.
 
CardLayout
The CardLayout object treats each component in the container as
a card. Only one card is visible at a time.
 
GridBagLayout
This is the most flexible layout manager class. The object of
GridBag Layout aligns the component vertically, horizontally or along
their baseline without requiring the components of same size.

15/03/2024 Akude P.A. 34


FlowLayout
 
FlowLayout is the default layout manager.
 
This is the layout manager that the preceding examples have used.

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
well as left and right.
is left between each component, above and below, as
 
Here are the constructors for

FlowLayout( ):-creates the default layout,
 which centers components and leaves five
pixels of space between each component.

 
FlowLayout(int how):- specify how each line is aligned. Valid values
 for
how(FowLayout.LEFT,FlowLayout.CENTER,FlowLayout.RIGHT,FlowLayout.LE
ADING,FlowLayout.TRAILING) These values specify left, center, right,
 leading edge, and trailing edge alignment, respectively.

FlowLayout(int how, int horz, int vert):-specify the horizontal
 and vertical space left
between components in horz and vert, respectively.

15/03/2024 Akude P.A. 35


15/03/2024 Akude P.A. 36
// Use left-aligned flow layout.
import java.awt.*;
import java.applet.*;
public class FlowLayoutDemo extends Applet
{
String msg = "";
Checkbox winXP, winVista, solaris,
mac; public void init() {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null,
true); winVista = new Checkbox("Windows
Vista"); solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
}

15/03/2024 Akude P.A. 37


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( ):- creates a default border layout.

BorderLayout(int horz, int vert):- 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.SOUTH,BorderLayout.EAST ,BorderLayout.WEST,
BorderLayout.NORTH.
• When adding components, you will use these constants with the following form
of add( ), which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component
will be added.

15/03/2024 Akude P.A. 38


15/03/2024 Akude P.A. 39
import java.applet.*;
import java.awt.*;
public class border extends Applet{
public void init()
{
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go
here."), BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n"
+ "Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}

}
15/03/2024 Akude P.A. 40
GridLayout


 The GridLayout is used to arrange the components
component is displayed in each rectangle.
 in rectangular grid. One

 
GridLayout lays out components in a two-dimensional grid.

 
you define the number of rows and columns.

 
The constructors supported by GridLayout are shown here:
  
GridLayout( )- creates a single-column grid layout

GridLayout(int numRows, int
numColumns)- creates a grid layout with the specified
 number of rows and columns

GridLayout(int numRows, int numColumns, int horz, int vert)- 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.

15/03/2024 Akude P.A. 41


15/03/2024 Akude P.A. 42
import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet
{ TextField tfv, tsv, tans;
Label lbf, lbs, lba;
Button btnSum; Panel
p1;
Panel p2; public
void init()
{lbf = new Label("Enter First value : "); lbs =
new Label("Enter Second Value : ");
lba=new Label("The Answer : ");
tfv = new TextField(); tsv=
new TextField(); tans = new
TextField(); btnSum = new
Button("Sum");
p1 = new Panel(new GridLayout(3,2));
p2 = new Panel(new
GridLayout(3,1)); add(p1); add(p2);
p1.add(lbf); p1.add(tfv);
p1.add(lbs); p1.add(tsv);
p1.add(lba);p1.add(tans)
p2.add(btnSum);
}
15/03/2024 Akude P.A. 43
}
CardLayout
• CardLayout class is unique among other layout
managers in that it stores several different layouts.
• The class CardLayout arranges each component in
the container as a card. Only one card is visible at
a time, and the container acts as a stack of cards.
• Constructors:

CardLayout()-
 Creates a new card layout with gaps of size
zero.

CardLayout(int hgap, int vgap)- Creates a new card layout
with the specified horizontal and vertical gaps.

15/03/2024 Akude P.A. 44


• Cards are typically held in an object of type Panel.
• Panel must have CardLayout selected as its
layout manager.
• The cards that form the deck are also
typically objects of type Panel.
• Thus, you must create a panel that contains
the deck and a panel for each card in the deck.
• Next, you add to the appropriate panel
the components that form each card.
• You then add these panels to the panel for
which CardLayout is the layout manager.
• Finally, you add this panel to the main
applet panel .
15/03/2024 Akude P.A. 45
• For Add component:
• void add(Component panelObj,
Object name);
example:
Panel p;
CardLayout cl;
Panel p1 = new Panel();
Panel p2 = new Panel();
p1.add(winXP);
p1.add(winVista);
p2.add(solaris);
p2.add(mac);
p.add(p1, "Windows");
p.add(p2, "Other");
15/03/2024 Akude P.A. 46
Methods:

void first(Container
 deck) : causes first card in deck
to be shown.
Ex:- cl.first(p);
Container deck means(Usually a panel)
 
void last(Container deck)
 
 void next(Container deck)
 
 void previous(Container deck)
 
void show(Container deck, String cardName)

15/03/2024 Akude P.A. 47


CardLayout Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class cardlayout extends Applet implements ActionListener {
Checkbox winXP, winVista, solaris, mac; Panel p;

CardLayout cl;
Button Win, Other;
public void init() {
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);
cl = new CardLayout();
p = new Panel();
p.setLayout(cl); // set panel layout to card layout
15/03/2024 Akude P.A. 48
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris"); mac = new
Checkbox("Mac OS");
Panel p1 = new Panel();
// add Windows check boxes to a
panel p1.add(winXP);
p1.add(winVista);
// add other OS check boxes to a panel
Panel p2 = new Panel();
p2.add(solaris);
p2.add(mac);
// add panels to card deck panel
p.add(p1, "Windows");
p.add(p2, "Other");
// add cards to main applet
panel add(p);
// register to receive action events
Win.addActionListener(this);
15/03/2024 Akude P.A. 49
Other.addActionListener(this); }
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == Win) {
cl.show(p, "Windows");
}
else {
cl.show(p, "Other");
}}}

15/03/2024 Akude P.A. 50


15/03/2024 Akude P.A. 51
GridBagLayout
• We take a bit more control over how the components
are arranged.
• A good way to do this is to use a grid bag layout, which
is specified by the GridBagLayout class.
• The grid bag useful is that you 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.

15/03/2024 Akude P.A. 52


• Each component managed by a grid bag layout is
associated with an instance of GridBagConstraints
that specifies how the component is laid out within its
display area.
• 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:

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.
 Constructor:
• GridBagLayout()
• you must use: setConstraints( ).
15/03/2024 Akude P.A. 53
• void setConstraints(Component comp,
GridBagConstraints cons)
• GridBagConstraints defines several fields that you can set
to govern the size, placement, and spacing of a component.

15/03/2024 Akude P.A. 54


15/03/2024 Akude P.A. 55
// Use GridBagLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GridBagDemo extends Applet
{
String msg = "";
Checkbox winXP, winVista, solaris,
mac; public void init() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new
GridBagConstraints(); setLayout(gbag);
// Define check boxes.
winXP = new Checkbox("Windows XP ", null,
true); winVista = new Checkbox("Windows
Vista"); solaris = new Checkbox("Solaris"); mac =
new Checkbox("Mac OS");
15/03/2024 Akude P.A. 56
// Define the grid bag.
// Use default row weight of 0 for first row.
gbc.weightx = 1.0; // use a column weight of
1 gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top
left gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(winXP, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(winVista, gbc);
// Give second row a weight of 1.
gbc.weighty = 1.0;

15/03/2024 Akude P.A. 57


gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac, gbc);
// Add the components.
add(winXP);
add(winVista);
add(solaris); add(mac);

}
// Display current state of the check
boxes. public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

15/03/2024 Akude P.A. 58


Menu Bars and Menus

15/03/2024 Akude P.A. 59


Menu Bars and Menus
• Menus are very familiar to a programmer in
Windows environment.
• A menu comes with a pull-down list of menu items
from which user can select one at a time.
• classes: MenuBar, Menu, and MenuItem
• A click on the MenuItem generates ActionEvent and
is handled by ActionListener.

15/03/2024 Akude P.A. 60


CheckboxMenuitem

15/03/2024 Akude P.A. 61


Steps of Creating Java AWT 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

15/03/2024 Akude P.A. 62


• Menu( )-The first form creates an empty menu.
• Menu(String optionName)
• Menu(String optionName, boolean removable)
• 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.
15/03/2024 Akude P.A. 63
• Individual menu items are of type MenuItem.
It defines these constructors:
• MenuItem( )
• MenuItem(String itemName)
• MenuItem(String itemName, MenuShortcut
keyAccel)
• itemName is the name shown in the menu,
and keyAccel is the menu shortcut for this
item.
15/03/2024 Akude P.A. 64
• setEnabled(boolean enabledFlag ):- disable or
enable a menu item Its form is
• isEnabled( ): determine an item’s .(true/false)
• setLabel(String newName):- change the name
of a menu item.
• getLabel( ).: ) returns the current name
• You can create a checkable menu item by
using a subclass of MenuItem called
CheckboxMenuItem[getState( ), setState( )]

15/03/2024 Akude P.A. 65


import java.awt.*;
import java.awt.event.*;
public class SimpleMenuExample extends Frame
{
Menu states, cities;
public SimpleMenuExample()
{
MenuBar mb = new MenuBar(); // begin with creating menu bar
setMenuBar(mb); // add menu bar to frame
states = new Menu("Indian States"); // create
menus cities = new Menu("Indian Cities");
mb.add(states); // add menus to menu bar
mb.add(cities);
states.add(new MenuItem("Himachal Pradesh"));
states.add(new MenuItem("Rajasthan"));
states.add(new MenuItem("West Bengal"));
states.addSeparator(); // separates from north Indian states from south Indian
states.add(new MenuItem("Andhra Pradesh"));
states.add(new MenuItem("Tamilnadu"));
15/03/2024 Akude P.A. 66
states.add(new MenuItem("Karnataka"));
cities.add(new MenuItem("Delhi"));
cities.add(new MenuItem("Jaipur"));
cities.add(new MenuItem("Kolkata"));
cities.addSeparator(); // separates north Indian cities from south
Indian cities.add(new MenuItem("Hyderabad"));
cities.add(new MenuItem("Chennai"));
cities.add(new MenuItem("Bengaluru"));

setTitle("Simple Menu Program"); // frame creation


methods setSize(300, 300);
setVisible(true);
}
public static void main(String args[])
{
new SimpleMenuExample();
}
}

15/03/2024 Akude P.A. 67


import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem
Example"); MenuBar mb=new MenuBar(); Menu
menu=new Menu("Menu");
Menu submenu=new Menu("Sub
Menu"); MenuItem i1=new
MenuItem("Item 1"); MenuItem i2=new
MenuItem("Item 2"); MenuItem i3=new
MenuItem("Item 3"); MenuItem i4=new
MenuItem("Item 4"); MenuItem i5=new
MenuItem("Item 5"); menu.add(i1);
menu.add(i2);
menu.add(i3);

15/03/2024 Akude P.A. 68


submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

15/03/2024 Akude P.A. 69


SWING
• There are two main ways to create a GUI in Java.
1. AWT(Abstract Window Toolkit)
2. Swing

• It is built on the top of AWT API and all objects in Swing are derived
from AWT, and most objects in Swing start with the letter J.
• Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications.
• Swing API is a set of extensible GUI Components to create
JAVA based Front End/GUI Applications.
• Java Swing is also known as Java GUI widget toolkit.
• Unlike AWT, Java Swing provides platform-independent
and lightweight components.
• Swing follow MVC architecture.
• Package: Import javax.swing.*;

15/03/2024 Akude P.A. 70


MVC Architecture
• Use MVC architecture.
• Model represents the data.(controls and components)
• View as a visual representation of the
data/determines how the component is displayed on
the screen (Container, LayoutManagers)
ex:button is displayed as a rectangle.
• Controller determines how the component responds
to the user ( acts as an interface between model and
view.)(Listener interface methods)
For example, when user presses a button, a new frame can
be displayed.
Swing is platform independent and enhanced
MVC (Model –View – Controller) framework for
Java application.
15/03/2024 Akude P.A. 71
Swing Features
• Lightweight Components: Swings is a part of Java Foundation Classes
(JFC) which are purely developed in Java. Also swing components require
less memory and CPU cycles than their counterpart AWT components.

• Pluggable Look and Feel: Swings supports pluggable look and feel i.e.,
the appearance of a component can be separated from how the
component behaves.

15/03/2024 Akude P.A. 72


Difference between AWT and Swing

15/03/2024 Akude P.A. 73


AWT Hierarchy Swing Hierarchy

15/03/2024 Akude P.A. 74


Components and Containers
• A component is an independent visual control.
a button, a slider, a label, ...
• A container holds a group of components.
• In order to display a component, it must be
placed in a container.
• Swing components are derived
from the JComponent class.
• JFrame, JApplet, JWindow, and Jdialog are
directly from AWT classes.
• All the component classes start with J: JLabel,
JButton, JScrollbar, ...

15/03/2024 Akude P.A. 75


Swing: JFrame Example
import java.awt.*;
import javax.swing.*;
public class fm {

public static void main ( String[] args )


{
JFrame f = new JFrame("JFrame Demo");
f.setSize(400,400);
f.setVisible( true );

f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}

15/03/2024 Akude P.A. 76


Create Simple Jframe
import javax.swing.*;
public class Swing_example
{
public static void main(String[] args)
{
JFrame frame1 = new JFrame();
JButton button1 = new JButton("button1");
JButton button2 = new JButton("button2");
button1.setBounds(180, 50, 80, 80);
button2.setBounds(180, 140, 80, 80);
frame1.add(button1);
frame1.add(button2);
frame1.setSize(500, 300)
; frame1.setLayout(null);
frame1.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
15/03/2024 Akude P.A. 77
}
Swing:Japplet Example
import javax.swing.*;
import java.awt.*;
public class MyApplet extends
JApplet {
JLabel label;
public void init()
{
setSize(600,300);
setLayout(new FlowLayout());
label = new JLabel("Applet using JApplet");
add(label);
}
}

15/03/2024 Akude P.A. 78


JButton
JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon


object.

• setText(String str):It is used to set specified text on button


• String getText() :It is used to return the text of the button.
• void setEnabled(boolean b) :It is used to enable or disable the button.
• void setIcon(Icon b): It is used to set the specified Icon on the button.
• Icon getIcon(): It is used to get the Icon of the button.

15/03/2024 Akude P.A. 79


JButton Example
JButton b=new JButton("Click
Here"); b.setBounds(50,100,95,30);
f.add(b);
JButton b=new JButton(new
ImageIcon("D:\\ico n.png"));

15/03/2024 Akude P.A. 80


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class gg extends JApplet {
JButton b;
JTextField tf,tp;
JLabel l,l1;
public void init() {
JPanel p=new JPanel();
p.setBorder(BorderFactory.createTitledBorder("LOGIN"));
p.setBackground(Color.GREEN);
tf=new JTextField(10); l=new
JLabel("User Name"); tp=new
JTextField(10); l1=new
JLabel("Password"); b=new
JButton("Login"); p.setLayout(new
GridLayout(3,2)); p.add(l);
p.add(tf);
p.add(l1); p.add(tp); p.add(b);
Container c=getContentPane();
c.setLayout(new FlowLayout());
15/03/2024 Akude P.A. 81
c.add(p);} }
15/03/2024 Akude P.A. 82
JLabel
JLabel l1,l2;
l1=new JLabel("First Label.");
add(l1);
• JLabel():Creates a label with no icon or text.
• JLabel(Icon image):Creates a label with a given icon.
• JLabel(Icon image, int horizontalAlignment):Creates a
label with a given icon and horizontal alignment.
• JLabel(String text):Creates a label with a given text.
• JLabel(String text, Icon icon, int horizontalAlignment):Creates
a label with a given text, icon, and horizontal alignment.
• JLabel(String text, int horizontalAlignment):Creates a label
with a given text and horizontal alignment.

15/03/2024 Akude P.A. 83


JComboBox
• ComboBox is a swing widget that displays a drop down list.
• JComboBox ()
• JComboBox(Object[] arr)
• Methods:
• void addItem(Object anObject): It is used to add an item to the item list.
• void removeItem(Object anObject) It is used to delete an item to the
item list.
• void removeAllItems()It is used to remove all the items from the list.
• void setEditable(boolean b)It is used to determine whether
the JComboBox is editable.
• void addActionListener(ActionListener a)It is used to
add the ActionListener.
• void addItemListener(ItemListener i)It is used to add the ItemListener.

15/03/2024 Akude P.A. 84


import javax.swing.*;
import java.awt.*;
import java.applet.*;
public class Combo extends Applet {
public void init(){
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country); cb.setBounds(50,
50,90,20);
add(cb);
setLayout(null);
setSize(400,500);
setVisible(true);
}

15/03/2024 Akude P.A. 85


JRadioButton
• The JRadioButton class is used to create a radio button. It is used
to choose one option from multiple options. It is widely used in
exam systems or quiz.
• Constructors:
• JRadioButton()
• JRadioButton(String s)
• JRadioButton(String s, boolean selected)
• Methods:
• void setText(String s),
• String getText().
• void setEnabled(boolean)
• void setIcon(Icon
• Icon getIcon()
• void addActionListener(ActionListener a)

15/03/2024 Akude P.A. 86


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements
ActionListener{ JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);

15/03/2024 Akude P.A. 87


setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String
args[]){ new RadioButtonExample();
}}

15/03/2024 Akude P.A. 88


15/03/2024 Akude P.A. 89
JProgressBar

• The JProgressBar class is used to display the progress


of the task. It inherits JComponent class.
• JProgressBar()
• JProgressBar(int min, int max)
• JProgressBar(int orient)
• JProgressBar(int orient, int min, int max)
• Methods:
• void setStringPainted(boolean b)
• void setString(String s)
• void setOrientation(int orientation)
• void setValue(int value)
15/03/2024 Akude P.A. 90
import javax.swing.*;
public class progress extends JFrame{
JProgressBar jb;
int i=0,num=0;
progress(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
progress m=new progress();
m.setVisible(true);
m.iterate();
15/03/2024 Akude P.A. 91
}
• You can create a tool tip for
any JComponent with setToolTipText()
metho d. This method is used to set up a tool
tip for the component.

15/03/2024 Akude P.A. 92


import javax.swing.*;
public class tooltip {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");

JPasswordField value = new JPasswordField();


value.setBounds(100,100,100,30);
value.setToolTipText("Enter your Password");
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

15/03/2024 Akude P.A. 93


JSeparator

• The object of JSeparator class is used to provide


a general purpose component for implementing
divider lines. It is used to draw a line to separate
widgets in a Layout.
• JSeparator()
• JSeparator(int orientation)
• Methods
• void setOrientation(int orientation)
• int getOrientation()

15/03/2024 Akude P.A. 94


import javax.swing.*;
class SeparatorExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
SeparatorExample() {
JFrame f= new JFrame("Separator Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
menu.add(i1);
menu.addSeparator();
menu.add(i2);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new SeparatorExample();
}}

15/03/2024 Akude P.A. 95


JTable

• The JTable class is used to display data in tabular form. It


is composed of rows and columns.
• JTable() Creates a table with empty cells.
• JTable(Object[][] rows, Object[] columns) Creates a
table with the specified data.

15/03/2024 Akude P.A. 96


import javax.swing.*;
public class jtable {
JFrame f;
jtable(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{ new jtable();
}
}

15/03/2024 Akude P.A. 97


JTree

• 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.
• JTree()
• JTree(Object[] value):Creates a JTree with every
element of the specified array as the child of a
new root node.
• JTree(TreeNode root):Creates a JTree with the
specified TreeNode as its root, which displays the
root node.
15/03/2024 Akude P.A. 98
import javax.swing.*;
import
javax.swing.tree.DefaultMutableTreeNode; public
class jtree extends JFrame {
JTree tree;
public jtree()
{ //create the root node
DefaultMutableTreeNode root = new
DefaultMutableTreeNode("Root"); //create the child nodes
DefaultMutableTreeNode veg = new DefaultMutableTreeNode("Vegetables");
veg.add(new DefaultMutableTreeNode("Capsicum"));
veg.add(new DefaultMutableTreeNode("Carrot"));
veg.add(new DefaultMutableTreeNode("Tomato"));
veg.add(new DefaultMutableTreeNode("Potato"));
DefaultMutableTreeNode fruit = new DefaultMutableTreeNode("Fruits");
fruit.add(new DefaultMutableTreeNode("Banana"));
fruit.add(new DefaultMutableTreeNode("Mango"));
fruit.add(new DefaultMutableTreeNode("Apple"));
fruit.add(new DefaultMutableTreeNode("Grapes"));
fruit.add(new DefaultMutableTreeNode("Orange"));
//add the child nodes to the root node
15/03/2024 Akude P.A. 99
root.add(veg);
root.add(fruit);

//create the tree by passing in the root


node tree = new JTree(root);

tree.setShowsRootHandles(true);
tree.setRootVisible(false);

add(tree);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTree Example"); this.setSize(200, 200);
this.setVisible(true);
}

public static void main(String[] args)


{
new jtree();
}
}

15/03/2024 Akude P.A. 100


JToggleButton

• JToggleButton is used to create toggle button,.


• it is two-states button to switch on or off.
• JToggleButton():It creates an initially unselected toggle button without setting the text or image.
• JToggleButton(Action a)It creates a toggle button where properties are taken from the
Action supplied.
• JToggleButton(Icon icon)It creates an initially unselected toggle button with the specified image
but no text.
• JToggleButton(Icon icon, boolean selected)It creates a toggle button with the specified image
and selection state, but no text.
• JToggleButton(String text)
• JToggleButton(String text, boolean selected)It creates a toggle button with the specified text
and selection state.
• JToggleButton(String text, Icon icon)It creates a toggle button that has the specified text and
image, and that is initially unselected.
• JToggleButton(String text, Icon icon, boolean selected)
• getAccessibleContext()It gets the AccessibleContext associated with this
JToggleButton.StringgetUIClassID()It returns a string that specifies the name of the l&f class
that renders this component.protected StringparamString()It returns a string representation of
this JToggleButton.voidupdateUI()

15/03/2024 Akude P.A. 101


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class toggle extends JFrame implements ItemListener
{ public static void main(String[] args) {
new toggle();
}
JToggleButton button;
toggle() {
setTitle("JToggleButton with ItemListener
Example"); setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
15/03/2024 Akude P.A. 102
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve)
{ if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}

15/03/2024 Akude P.A. 103

You might also like