0% found this document useful (0 votes)
0 views114 pages

Advance Java Unit 1

Uploaded by

Devendra Marathe
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)
0 views114 pages

Advance Java Unit 1

Uploaded by

Devendra Marathe
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/ 114

Advance Java Programming

Unit 1
Unit I Applet ( 6
Hrs)
 Applet Basics – Introduction, limitations of AWT.
 Applet architecture – HTML APPLET tag – Passing parameter to
Applet.
 getDocumentBase() and getCodeBase()
 Japplet: Icons and Labels Text Fields Buttons, Combo Boxes ,
Checkboxes
 Tabbed Panes, Scroll Panes, Trees,Tables

2
Advance Java Books : Books
TEXT BOOKS
T1. Herbert Schildt, “Java: The complete reference”, Tata McGraw Hill, 7th Edition
T2. Jim Keogh, “Complete Reference J2EE” , Enterpr
T3. E. Balaguruswamy, “Programming with JAVA: A Primer” McGraw Hill Education, India, 5th Edition
REFERENCE BOOKS
R1. “Java 6 Programming”, Black Book, Dreamtech
R2. “Java Server Programming, Java EE6 (J2EE 1.6)”, Black Book, Dreamtech
R3. M.T. Savaliya,“Advanced Java Technology”, Dreamtech
ADDITIONAL MATERIAL
MOOC / NPTEL:
1. NPTEL Course “Programming in Java” https://nptel.ac.in/courses/106/105/106105191/
2. Udemy course “Advanced Java Programming” https://www.udemy.com/course/advanced-java-
programming

3
Teaching Methodology: Topic – Book –
Pages/online site Mapping
Reference / text book
Sr. No. Topic
with page
no./web
refrence
UNIT 1: Applet

1  Applet Basics – Introduction, limitations of AWT.


T1
 Applet architecture – HTML APPLET tag – Passing parameter to Applet.
Chapter 21
 getDocumentBase() and getCodeBase()

2  Japplet: Icons and Labels Text Fields Buttons, Combo Boxes , Checkboxes

 Tabbed Panes, Scroll Panes, Trees,Tables


T1
Chapter 29-30

4
Applet
A Java applet is a special kind of Java program that a browser enabled with
Java technology can download from the internet and run. An applet is
typically embedded inside a web page and runs in the context of a browser.
An applet must be a subclass of the java.applet.Applet class. The Applet
class provides the standard interface between the applet and the browser
environment.
Applets
 An applet is a Java program that runs in a Web browser.
 An applet can be a fully functional Java application because
it has the entire Java API at its disposal.

6
Applets
 Applets based on the AWT(Abstract Window
Toolkit) package by extending its Applet class.
 Applets based on the Swing package by extending
its JApplet class
Applet Life Cycle in Java
Applet Life Cycle in Java
 init(): The init() method is the first method to run that initializes
the applet.
 It can be invoked only once at the time of initialization.
 The web browser creates the initialized objects, i.e., the web
browser runs the init() method within the applet.
Applet Life Cycle in Java
 start(): The start() method contains the actual code of the applet
and starts the applet.
 It is invoked immediately after the init() method is invoked.
 Every time the browser is loaded or refreshed, the start()
method is invoked.
 It is also invoked whenever the applet is maximized, restored, or
moving from one tab to another in the browser.
 It is in an inactive state until the init() method is invoked.
Applet Life Cycle in Java
 stop(): The stop() method stops the execution of the applet.
 The stop () method is invoked whenever the applet is
stopped, minimized, or moving from one tab to another in
the browser, the stop() method is invoked.
 When we go back to that page, the start() method is invoked
again.
Applet Life Cycle in Java
 destroy(): The destroy() method destroys the applet after its
work is done.
 It is invoked when the applet window is closed or when the
tab containing the webpage is closed.
 It removes the applet object from memory and is executed
only once.
 We cannot start the applet once it is destroyed .
Applet Life Cycle in Java
paint(): The paint() method belongs to the Graphics class in
Java.
It is used to draw shapes like circle, square, trapezium, etc.,
in the applet.
It is executed after the start() method and when the browser
or applet windows are resized.
import java.awt.*;
import java.applet.*;
Example public class Applet1 extends Applet
{
public void init()
{System.out.println("Initializing an applet");}
public void start()
{System.out.println("Starting an applet");}
public void stop()
{System.out.println("Stopping an applet");}
public void destroy()
{System.out.println("Destroying an applet");}
}
Specifying Local applet
<applet
Example codebase = "tictactoe"
code = " HelloWorldApplet.class"
width = 120
import java.applet.*;
height = 120>
import java.awt.*; </applet>
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g) { Specifying Remote applet
<applet
g.drawString ("Hello World", 25, 50); codebase = "http://www.myconnect.com/applets/"
} code = " HelloWorldApplet.class"
width = 120
} height =120>
</applet>
package EXAMPLE;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class PRACAPP extends Applet{


public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Hello TE IN APPLETS",50, 50);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}
getCodeBase() - getDocumentBase()
 The getCodebase() method is also commonly used to
establish a path to other files or folders that are in the same
location as the class being run.
 The getDocumentBase() method is used to return the URL of
the directory in which the document is resides.
 URL getCodeBase(): Gets the base URL.
 URL getDocumentBase(): Gets the URL of the document in
which the applet is embedded
Example
import java.applet.Applet;
import java.awt.Graphics;
public class MyAppletClass extends Applet {
public void paint(Graphics g) {
g.drawString("getCodeBase : "+getCodeBase(), 20,
20);

g.drawString("getDocumentBase:"+getDocumentBase(),20,40
);
}
}
Example getCodeBase() - getDocumentBase()
How to get the object of Image
 The java.applet.Applet class provides getImage() method
that returns the object of Image.
 Syntax:
 public Image getImage(URL u, String image){}
 public abstract boolean drawImage(Image img, int x, int
y, ImageObserver observer): is used draw the specified
image.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
public class PRACAPP extends Applet{
Image img1;
public void init()
{
img1=getImage(getDocumentBase(),“Mickey.jpg");}
public void paint(Graphics g)
{g.drawImage(img1,100,30,this);}
}
Explanation
 In the above example, drawImage() method of Graphics
class is used to display the image.
 The 4th argument of drawImage() method of is
ImageObserver object.
 The Component class implements ImageObserver interface.
 So current class object would also be treated as
ImageObserver because Applet class indirectly extends the
Component class.
Java applet example - get applet
parameters from an HTML file
 Many times when you're developing a Java applet, you want
to pass parameters from an HTML page to the applet you're
invoking.
 For instance, you may want to tell the applet what
background color it should use, or what font to use, to keep
your Java applet consistent with the rest of your HTML-
based web site.
Java applet example - get applet
parameters from an HTML file
 A great benefit of passing applet parameters from HTML
pages to the applets they call is portability.
 If you pass parameters into your Java applets, they can be
portable from one web page to another, and from one web
site to another.
 On the other hand, if you don't pass parameters into a Java
applet, how will the applet know what font to use.
Java applet example - get applet
parameters from an HTML file
 We can get any information from the HTML file as a
parameter.
 For this purpose, Applet class provides a method named
getParameter().
 public String getParameter(String parameterName)
Example
import java.applet.Applet;
import java.awt.Graphics;
public class MyAppletClass extends Applet {
String str=null;
public void init()
{
str=getParameter("msg");
}
public void paint(Graphics g)
{
g.drawString(str,50, 50);
}
}
AWT - Abstract Window Toolkit
 It is a platform-dependent API to develop GUI (Graphical
User Interface) or window-based applications in Java.
 It was developed by Sun Microsystem In 1995.
 It is heavy-weight in use because it is generated by the
system’s host operating system.
 It contains a large number of classes and methods, which
are used for creating and managing GUI.
Characteristics
 It is a set of native user interface components.
 It is very robust in nature.
 It includes various editing tools like graphics tool and
imaging tools.
 It uses native window-system controls.
 It provides functionality to include shapes, colors and font
classes.
Disadvantages OF AWT
 The buttons of AWT does not support pictures.
 It is heavyweight in nature.
 Two very important components trees and tables are not
present.
 Extensibility is not possible as it is platform dependent
SWING
 Swing is a set of classes this provides more powerful and flexible
components than are possible with the AWT.
 A Swing GUI consists of two key items: components and containers.
 In addition to the familiar components, such as buttons, check
boxes, and labels, Swing supplies several exciting additions,
including tabbed panes, scroll panes, trees, and tables.
 Even familiar components such as buttons have more capabilities in
Swing.
 For example, a button may have both an image and a text string
associated with it.
SWING
 Also, the image can be changed as the state of the button changes.
 Unlike AWT components, Swing components are not implemented
by platform-specific code.
 Instead, they are written entirely in Java and, therefore, are
platform-independent.
 The term lightweight is used to describe such elements.
 Swing is the set of packages built on top of the AWT that provide us
with a great number of pre-built classes that is, over 250 classes
and 40 UI components.
Swings
 Swing defines two types of containers.
 The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
 These containers do not inherit JComponent.
 They do, however, inherit the AWT classes Component and Container.
 The 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
Components
Swings
 JTree Encapsulates a tree-based control.
 The Swing-related classes are contained in javax.swing and its
subpackages.
Swing Features
 Besides the large array of components in Swing and the fact that they
are lightweight, Swing introduces many other innovations.
 Borders
 We can draw borders in many different styles around components
using the setborder( ) method.
 Graphics Debugging
 We can use setDebugging GraphicsOptions method to set up
graphics debugging which means among the other things, that you
can watch each line as its drawn and make it flash.
Swing Features
 Easy mouseless operation
 It is easy to connect keystrokes to components.
 Tooltips
 We can use the setToolTipText method of JComponent to
give components a tooltip, one of those small windows
that appear when the mouse hovers over a component
and gives explanatory text.
Swing Features
 Easy Scrolling
 We can connect scrolling to various components-something that was
impossible in AWT.
 Pluggable look and feel
 We can set the appearance of applets and applications to one of
three standard looks.
 Windows, Motif (Unix) or Metal (Standard swing look).
 New Layout Managers
 Swing introduces the BoxLayout and OverlayLayout layout
managers.
Class Description
 AbstractButton -Abstract super-class for Swing buttons.
 ButtonGroup - Encapsulates a mutually exclusive set of
buttons.
 ImageIcon - Encapsulates an icon.
 JApplet -The Swing version of Applet.
 JButton- The Swing push button class.
 JCheckBox -The Swing check box class.
Class Description
 JComboBox -Encapsulates a combo box (a combination of a
dropdown list and text field).
 JLabel -The Swing version of a label.
 JRadioButton -The Swing version of a radio button.
 JScrollPane- Encapsulates a scrollable window.
 JTabbedPane -Encapsulates a tabbed window.
 JTable -Encapsulates a table-based control.
 JTextField -The Swing version of a text field.
 Jtree- Encapsulates a tree-based control.
JApplet
 Fundamental to Swing is the JApplet class, which extends
Applet.
 Applets that use Swing must be subclasses of JApplet.
 Swing applets use the same four lifecycle : init( ), start( ),
stop( ), and destroy( ).
 JApplet is a top-level Swing container, which means that it is
not derived from Jcomponent.
 JApplet is derived from Applet.
 JApplet is rich with functionality that is not found in Applet.
JApplet
 For example, JApplet supports various “panes,” such as the
content pane, the glass pane, and the root pane.
 When adding a component to an instance of JApplet, do not
invoke the add( ) method of the applet.
 Instead, call add( ) for the content pane of the JApplet
object.
 The content pane can be obtained via the method shown
here:
 Container getContentPane( )
JApplet
 The add( ) method of Container can be used to add a
component to a content pane.
 Its form is shown here:
 void add(comp)
 Here, comp is the component to be added to the content
pane.
Icons and Labels
 In Swing, icons are encapsulated by the ImageIcon class,
which paints an icon from an image.
 Two of its constructors are shown here:
 ImageIcon(String filename)
 ImageIcon(URL url)
 The first form uses the image in the file named filename.
 The second form uses the image in the resource
identified by url.
Icons and Labels
 The ImageIcon class implements the Icon interface that declares the
methods shown here:
 int getIconHeight( )
 Returns the height of the icon in pixels.
 int getIconWidth( )
 Returns the width of the icon in pixels.
 void paintIcon(Component comp, Graphics g, int x, int y)
 Paints the icon at position x,y on the graphics context g. Additional
information about the paint operation can be provided in comp.
Icons and Labels
 Swing labels are instances of the JLabel class, which extends
JComponent. It can display text and/or an icon.
 It is a passive component in that it does not respond to user input.
 Some of its constructors are shown here:
 JLabel(Icon i)
 Label(String s)
 JLabel(String s, Icon i, int align)
 Here, s and i are the text and icon used for the label.
 The align argument is either LEFT, RIGHT,CENTER, LEADING, or
TRAILING
Icons and Labels
 The icon and text associated with the label can be read and
written by the following methods:
 Icon getIcon( )
 String getText( )
 void setIcon(Icon i)
 void setText(String s)
 Here, i and s are the icon and text, respectively
Example

import java.awt.*;
import javax.swing.*;
public class JLabelDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
contentPane.add(jl);
}
}
getContentPane()
 A container has several layers in it.
 In Java Swing, the layer that is used to hold objects is called
the content pane.
 Objects are added to the content pane layer of the container.
 The getContentPane() method retrieves the content pane layer
so that you can add an object to it.
 When you use getContentPane(), the content pane object then
is substituted there so that you can apply a method to it.
Text Fields
 The Swing text field is encapsulated by the JTextComponent class, which
extends JComponent.
 It provides functionality that is common to Swing text components.
 One of its subclasses is JTextField, which allows us to edit one line of text.
 Some of its constructors are shown here:
 JTextField( )
 JTextField(int cols)
 JTextField(String s, int cols)
 JTextField(String s)
 Here, s is the string to be presented, and cols is the number of columns in the
text field.
Example
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
Java FlowLayout
 The Java FlowLayout class is used to arrange the components in a
line, one after another (in a flow).
 It is the default layout of the applet or panel.
 Fields of FlowLayout class
 public static final int LEFT
 public static final int RIGHT
 public static final int CENTER
 public static final int LEADING
 public static final int TRAILING
JButtons
 Swing buttons provide features that are not found in the Button class defined
by the AWT.
 For example, we can associate an icon with a Swing button.
 Swing buttons are subclasses of the AbstractButton class, which extends
JComponent.
 AbstractButton contains many methods that allow us to control the behavior
of buttons, check box and radio buttons.
 For example, we can define different icons that are displayed for the
component when it is disabled, pressed, or selected.
 Another icon can be used as rollover icon, which is displayed when the
mouse is positioned over that component.
JButtons
 The following are the methods that control this behavior:
 void setDisabledIcon(Icon di)
 void setPressedIcon(Icon pi)
 void setSelectedIcon(Icon si)
 void setreadIcon(Icon ri)

 Here, di, pi, si, and ri are the icons to be used for these different
 conditions.
JButtons
 The text associated with a button can be read and written via
the following methods:
 String getText( )
 void setText(String s)
 Here, s is the text to be associated with the button.
JButtons
 Concrete subclasses of AbstractButton generate action
events when they are pressed.
 Listeners register and un-register for these events via the
methods shown here:
 void addActionListener(ActionListener al)
 void removeActionListener(ActionListener al)
 Here, al is the action listener. AbstractButton is a superclass
for push buttons, check boxes, and radio buttons.
JButton Class
 The JButton class provides the functionality of a push
button.
 Jbutton allows an icon string, or both to be associated with
the push button.
 Some of its constructors are shown here:
 JButton(Icon i)
 JButton(String s)
 JButton(String s, Icon i)
 Here, s and i are the string and icon used for the button.
JButton
package example;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JTextField;
JButton
public class JLabelDemo extends JApplet implements ActionListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("green.jpg");
JButton jb = new JButton(france);
jb.setActionCommand("Green");
jb.addActionListener(this);
contentPane.add(jb);
JButton
ImageIcon germany = new ImageIcon("red.jpg");
jb = new JButton(germany);
jb.setActionCommand("Red");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("yellow.jpg");
jb = new JButton(italy);
jb.setActionCommand("Yellow");
jb.addActionListener(this);
contentPane.add(jb);
JButton
ImageIcon japan = new ImageIcon("black.jpg");
jb = new JButton(japan);
jb.setActionCommand("Black");
jb.addActionListener(this);
contentPane.add(jb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}}
checkboxes
 The JCheckBox class, which provides the functionality of a
check box, is a concrete implementation of AbstractButton.
 It is immediate super-class is JToggleButton, which
provides support for two-state buttons
JCheckBox constructor
 JCheckBox(Icon i)
 JCheckBox(Icon i, boolean state)
 JCheckBox(String s)
 JCheckBox(String s, boolean state)
 JCheckBox(String s, Icon i)
 JCheckBox(String s, Icon i, boolean state)
 Here, i is the icon for the button. The text is specified by s.
 If state is true, the check box is initially selected.
Example

cb.addItemListener(this);
public class JCheckBoxDemo extends JApplet contentPane.add(cb);
implements ItemListener jtf = new JTextField(15);
{ contentPane.add(jtf);
JTextField jtf; }
public void init() public void itemStateChanged(ItemEvent ie)
{ {
Container contentPane = getContentPane(); JCheckBox cb = (JCheckBox)ie.getItem();
contentPane.setLayout(new FlowLayout()); jtf.setText(cb.getText());
JCheckBox cb = new JCheckBox("C", true); }
cb.addItemListener(this);
contentPane.add(cb); }
cb = new JCheckBox("C++", false);
Radio Buttons
 Radio buttons are supported by the JRadioButton class, which is a concrete
implementation of AbstractButton.
 Its immediate super-class is JToggleButton, which provides support for two-state
buttons.
 Some of its constructors are shown here:
 JRadioButton(Icon i)
 JRadioButton(Icon i, boolean state)
 JRadioButton(String s)
 JRadioButton(String s, boolean state)
 JRadioButton(String s, Icon i)
 JRadioButton(String s, Icon i, boolean state)
import java.awt.*;
import java.awt.event.*;
Example import javax.swing.*;
public class JRadioButtonDemo extends JApplet implements
ActionListener
{
JTextField tf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B"); bg.add(b3);
b2.addActionListener(this); tf = new JTextField(5);
contentPane.add(tf);
contentPane.add(b2); }
JRadioButton b3 = new JRadioButton("C"); public void actionPerformed(ActionEvent ae)
{
b3.addActionListener(this);
tf.setText(ae.getActionCommand());
contentPane.add(b3); }
ButtonGroup bg = new ButtonGroup(); }

bg.add(b1);
bg.add(b2);
Comboboxes
 Swing provides a combo box (a combination of a text field
and a dropdown list) through the JComboBox class, which
extends JComponent.
 A combo box normally displays one entry.
 However, it can also display a drop-down list that allows a
user to select a different entry.
Comboboxes
 We can also type our selection into the text field. Two of JComboBox’s
constructors are shown here:
 JComboBox( )
 JComboBox(Vector v)
 JComboBox(Objects obj[])
 Here, v is a vector that initializes the combo box and obj is the array of
objects. Items are added to the list of choices via the addItem( )
method, whose signature is shown here:
 void addItem(Object obj)
 Here, obj is the object to be added to the combo box.
Important methods
 public void setEditable(boolean aFlag)
 It determines whether the JComboBox field is editable or not?
 public boolean isEditable()
 It returns true if the JComboBox is editable. By default, a combo box is
not editable.
 public void setMaximumRowCount(int count)
 It sets the maximum number of rows the JComboBox displays. If the
number of objects in the model is greater than ‘count’, the combo box
uses a scrollbar.
 public void setSelectedItem(Object anObject)
 It sets the selected item in the combo box display area to the object in the
argument. If anObject is in the list, the display area shows an Object selected.
 public void insertItemAt(Object anObject, int index)
 It inserts an item ‘anObject’ into the item list at a given ‘index’.
 public void removeItem(Object anObject)
 It removes an item ‘anObject’ from the item list.
 public void removeItemAt(int anIndex)
 It removes the item at ‘anIndex’.
public class Myapplet extends JApplet implements jc.addItem("Yellow");
ItemListener
jc.addItemListener(this);
{
contentPane.add(jc);
JLabel jl;
jl = new JLabel(new
ImageIcon green, red, black, yellow; ImageIcon("green.jpg"));
@SuppressWarnings("unchecked")
contentPane.add(jl);
public void init()
}
{
public void itemStateChanged(ItemEvent ie)
Container contentPane = getContentPane();
{
contentPane.setLayout(new FlowLayout());
String s = (String)ie.getItem();
@SuppressWarnings("rawtypes")
if(s=="Green")
JComboBox jc = new JComboBox();
jl.setIcon(new ImageIcon(s + ".jpg"));
jc.addItem("Green");
if(s=="Black")
jc.addItem("Red");
jl.setIcon(new ImageIcon(s + ".jpg"));
jc.addItem("Black");
}
}
Tabbed Panes
 A tabbed pane is a component that appears as a group of folders in a
file cabinet.
 Each folder has a title.
 When a user selects a folder, its contents become visible.
 Only one of the folders may be selected at a time.
 Tabbed panes are commonly used for setting configuration options.
 Tabbed panes are encapsulated by the JTabbedPane class, which
extends JComponent.
Tabbed Panes
 There are three constructors of JTabbedPane.
 JTabbedPane()
 JTabbedPane(int tabPlacement)
 JTabbedPane(int tabPlacement, int tabLayoutPolicy)
 The first form creates an empty TabbedPane with a default tab placement of
JTabbedPane.TOP.
 Second form creates an empty TabbedPane with the specified tab placement of any of the
following:
 JTabbedPane.TOP
 JTabbedPane.BOTTOM
 JTabbedPane.LEFT
 JTabbedPane.RIGHT
Tabbed Pane
 The third form of constructor creates an empty TabbedPane with the
specified tab placement and tab layout policy.
 Tab layout policy may be either of the following:
 JTabbedPane.WRAP_TAB_LAYOUT

 JTabbedPane.SCROLL_TAB_LAYOUT
Tabbed Pane
 Tabs are defined via the following method:
 void addTab(String str, Component comp)
 Here, str is the title for the tab, and comp is the component that should be
added to the tab. Typically, a JPanel or a subclass of it is added.
 The general procedure to use a tabbed pane in an applet is outlined here:
 Create a JTabbedPane object.
 Call addTab( ) to add a tab to the pane
 Repeat step 2 for each tab.
 Add the tabbed pane to the content pane of the applet
import javax.swing.*; class ColorsPanel extends JPanel
class LangPanel extends JPanel {
{ public ColorsPanel()
public LangPanel() {
{
JCheckBox cb1 = new JCheckBox("Red");
JButton b1 = new JButton("Marathi");
add(cb1);
add(b1);
JCheckBox cb2 = new
JButton b2 = new JButton("Hindi"); JCheckBox("Green");
add(b2);
add(cb2);
JButton b3 = new JButton("Bengali");
JCheckBox cb3 = new
add(b3); JCheckBox("Blue");
JButton b4 = new JButton("Tamil"); add(cb3);
add(b4); }
}
}
}
class FlavorsPanel extends JPanel public class Myapplet extends JApplet
{ {
public FlavorsPanel() public void init()
{ {
JComboBox<String> jcb = new JTabbedPane jtp = new JTabbedPane();
JComboBox<String>();
jtp.addTab("Languages", new LangPanel());
jcb.addItem("Vanilla");
jtp.addTab("Colors", new ColorsPanel());
jcb.addItem("Chocolate");
jtp.addTab("Flavors", new FlavorsPanel());
jcb.addItem("Strawberry");
getContentPane().add(jtp);
add(jcb);
}
}
}
}
Scroll Panes
 JScrollPane is a lightweight container that automatically handles the
scrolling of another component.
 If the object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided, and the component
can be scrolled through the pane.
 The viewable area of a scroll pane is called the viewport.
Scroll Panes
 The scroll bars scroll the component through the viewport.
 In its default behavior, a JScrollPane will dynamically add or remove a
scroll bar as needed.
 Forexample, if the component is taller than the viewport, a vertical
scroll bar is added.
 If the component will completely fit within the viewport, the scroll bars
are removed.
https://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html
Scroll Panes
 Some of its constructors are shown here:
 JScrollPane()
 JScrollPane(Component comp)
 JScrollPane(int vsb, int hsb)
 JScrollPane(Component comp, int vsb, int hsb)
 Here, comp is the component to be added to the scroll pane. vsb and
hsb are int constants that define when vertical and horizontal scroll
bars for this scroll pane are shown.
 These constants are defined by the ScrollPaneConstants interface.
Scroll Panes
 Some examples of these constants are described as follows:
 Constant Description
 HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scrollbar
 HORIZONTAL_SCROLLBAR_AS_NEEDED Provide horizontal scroll bar,
ifneeded
 VERTICAL_SCROLLBAR_ALWAYS Always provide vertical scrollbar
 VERTICAL_SCROLLBAR_AS_NEEDED Provide vertical scroll bar, if needed
Scroll Panes
 Here are the steps that you should follow to use a scroll pane in an
applet:
 Create a JComponent object.
 Create a JScrollPane object. (The arguments to the constructor specify
the component and the policies for vertical and horizontal scroll bars.)
 Add the scroll pane to the content pane of the applet.
import java.awt.BorderLayout; for(int i = 0; i < 20; i++)
import java.awt.Container; {
import java.awt.GridLayout; for(int j = 0; j < 20; j++)
import javax.swing.*; {
jp.add(new JButton("Button " + b));
++b;
public class Myapplet extends JApplet
}
{
}
public void init()
int v = ScrollPaneConstants.
{ VERTICAL_SCROLLBAR_AS_NEEDED;
Container contentPane = getContentPane(); int h = ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_AS_NEEDED;
contentPane.setLayout(new
JScrollPane jsp = new JScrollPane(jp, v, h);
BorderLayout());
contentPane.add(jsp, BorderLayout.CENTER);
JPanel jp = new JPanel();
}
jp.setLayout(new GridLayout(20, 20));
int b = 0;
}
JTREES
 A tree is a component that presents a hierarchical view of data.
 A user has the ability to expand or collapse individual sub-trees in this
display.
JTREES
 Trees are implemented in Swing by the JTree class, which extends
 JComponent. Some of its constructors are shown here:
 JTree(Hashtable ht)
 JTree(Object obj[ ])
 JTree(TreeNode tn)
 JTree(Vector v)
 The first form creates a tree in which each element of the hash table ht is a child node.
 Each element of the array obj is a child node in the second form.
 The tree node tn is the root of the tree in the third form.
 Finally, the last form uses the elements of vector v as child nodes.
JTREES
 JTree is packaged in javax.swing, its support classes and
interfaces are packaged in javax.swing.tree.
 JTree relies on two models: TreeModel and
TreeSelectionModel.
 A JTree generates a variety of events, but three relate
specifically to trees: TreeExpansionEvent,
TreeSelectionEvent, and TreeModelEvent.
JTREES
 TreeExpansionEvent events occur when a node is expanded or
collapsed.
 A TreeSelectionEvent is generated when the user selects or
deselects a node within the tree.
 ATreeModelEvent is fired when the data or structure of the tree
changes.
 The listeners for these events are TreeExpansionListener,
TreeSelectionListener, and TreeModelListener, respectively
TREES
 The addTreeExpansionListener( ) and removeTreeExpansionListener()
methods allow listeners to register and unregister for these
notifications.
 The signatures of these methods are shown here:
 void addTreeExpansionListener(TreeExpansionListener tel)
 void removeTreeExpansionListener(TreeExpansionListener tel)
 Here, tel is the listener object.
TREES
 The getPathForLocation( ) method is used to translate a mouse click on a
specific point of the tree to a tree path.
 Its signature is shown here:
 TreePath getPathForLocation(int x, int y)
 Here, x and y are the coordinates at which the mouse is clicked.
 The TreePath class encapsulates information about a path to a particular
node in a tree.
 It provides several constructors and methods.
TREES
 The TreeNode interface declares methods that obtain information
about a tree node.
 For example, it is possible to obtain a reference to the parent node or
an enumeration of the child nodes.
 The MutableTreeNode interface extends TreeNode.
 It declares methods that can insert and remove child nodes or change
the parent node.

 https://www.codejava.net/java-se/swing/jtree-basic-tutorial-and-examples#:~:text=JTree%20is%20a%20Swing%20component,an%20item%2
0in%20a%20tree.&text=If%20a%20node%20doesn't,is%20called%20a%20leaf%20node
.
TREES
The DefaultMutableTreeNode class implements the MutableTreeNode
interface. It represents a node in a tree.
One of its constructors is shown here:

DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node
Tree
 To create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used.
 Its signature is shown here:
 void add(MutableTreeNode child)
 Here, child is a mutable tree node that is to be added as a child to the
current node.
TREES
Here are the steps that we should follow to use a tree in an applet:
Example
public class Example extends JApplet
{
JTree tree;
JTextField jtf;
public void init()
{
Container contentPane=getContentPane();
contentPane.setLayout(new BorderLayout());
DefaultMutableTreeNode top=new DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a= new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1=new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2=new DefaultMutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode b= new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1=new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2=new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3=new DefaultMutableTreeNode("B3");
b.add(b3);
tree=new JTree(top);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tree,v,h);
contentPane.add(jsp,BorderLayout.CENTER);
jtf=new JTextField("",20);
contentPane.add(jtf,BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me)
{
TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}
Explanation
 The init( ) method gets the content pane for the applet.

 A DefaultMutableTreeNode object labeled Options is created.

 This is the top node of the tree hierarchy. Additional tree nodes are then created, and
the add( ) method is called to connect these nodes to the tree.
 A reference to the top node in the tree is provided as the argument to the JTree
constructor.
 The tree is then provided as the argument to the JScrollPane constructor.

 This scroll pane is then added to the applet. Next, a text field is created and added to
the applet.
 Information about mouse click events is presented in this text field.
Explanation
 To receive mouse events from the tree, the addMouseListener( ) method of the JTree
object is called.
 The argument to this method is an anonymous inner class that extends
MouseAdapter and overrides the mouseClicked( ) method.
 The doMouseClicked( ) method processes mouse clicks.
 It calls getPathForLocation( ) to translate the coordinates of the mouse click into a
TreePath object.
 If the mouse is clicked at a point that does not cause a node selection, the return
value from this method is null.
 Otherwise, the tree path can be converted to a string and presented in the text field.
 The string presented in the text field describes the path from the top tree node to the
selected node.
JTables
 A table is a component that displays rows and columns of data.
 We can drag the cursor on column boundaries to resize columns.
 We can also drag a column to a new position.
 Tables are implemented by the JTable class, which extends
JComponent.
JTables
 One of its constructors is shown here:
 JTable(Object data[ ][ ], Object colHeads[ ])
 JTable(int numRows, int numColumns)
 JTable(Vector rowData, Vector columnData)
 Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
 The ‘numRows’ and ‘numColumns’ are values with which the table is to be
created.
 The ‘rowData’ and ‘columnData’ are the vector values by which the table is
constructed.
JTables
 JTable relies on three models. The first is the table model, which is
defined by the
 TableModel interface. This model defines those things related to
displaying data in a two-dimensional format.
 TableColumnModel. specifies the characteristics of a column
 ListSelectionModel.
JTables
 AJTable can generate several different events.
 The two most fundamental to a table’s operation are ListSelectionEvent and
TableModelEvent.
 A ListSelectionEvent is generated when the user selects something in the
table.
 By default, JTable allows you to select one or more complete rows, but you can
change this behavior to allow one or more columns, or one or more individual
cells to be selected.
 A TableModelEvent is fired when that table’s data changes in some way.
Handling these events requires a bit more work than it does to handle the events
generated by the previously described components
JTables
 Here are the steps for using a table in an applet:
 1) Create a JTable object.
 2) Create a JScrollPane object. (The arguments to the constructor
specify the table and the policies for vertical and horizontal scroll bars.)
 3) Add the table to the scroll pane.
 4) Add the scroll pane to the content pane of the applet.
Example
import java.awt.*;
import javax.swing.*;
public class Example extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
final String[] colHeads = { "Name", "Phone", "Fax" };
final Object[][] data = {{ "Pramod", "4567", "8675" },
{ "Tausif", "7566", "5555" },
{ "Nitin", "5634", "5887" },
{ "Amol", "7345", "9222" },
{ "Vijai", "1237", "3333" },
{ "Ranie", "5656", "3144" },
{ "Mangesh", "5672", "2176" },
{ "Suhail", "6741", "4244" },
{ "Nilofer", "9023", "5159" },
{ "Jinnie", "1134", "5332" },
{ "Heena", "5689", "1212" },
{ "Saurav", "9030", "1313" },
{ "Raman", "6751", "1415" }
};
JTable table = new JTable(data, colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h =
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
}
}
Explanation
 The following example illustrates how to create and use a table.
 The content pane of the JApplet object is obtained and a border layout is
assigned as its layout manager.
 A one-dimensional array of strings is created for the column headings.
 This table has three columns.
 A two-dimensional array of strings is created for the table cells. We can
see that each element in the array is an array of three strings.
 These arrays are passed to the JTable constructor.
 The table is added to a scroll pane and then the scroll pane is added to
the content pane.
Assignment
1) Using java swings component create login page.(use JApplet / JFrame)
Hint: Two Jlabels, two Jtextfields.
On JButton click event dialog box should appear saying login successful.
References
1. Java 2 the Complete Reference,
Herbert Schildt, 2001 Osborne McGraw Hill
Chapter 26: The Tour of Swing
(Most of the data is referred from this book)
2. Java 6 Black Book,
Kogent Solutions, 2007, Dreamtech Press
Chapter 15: Swing–Applets, Applications and Pluggable Look and
Feel.
3. JDK 5.0 Documentation
Additional Online available Link/
Reference books
 https://cse.iitkgp.ac.in/~dsamanta/java/ch10.htm
 https://www.youtube.com/watch?v=Tch-CpttcOc
 How to install window builder in eclipse: https://www.youtube.com/watch?v=oeswfZ
z4IW0
 Java Eclipse GUI Tutorial by drag and drop
 https://www.youtube.com/watch?v=r8Qiz9Bn1Ag
 https://www.youtube.com/watch?v=-GoqPrxM8TQ

You might also like