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

Advanced Java UNit II

Uploaded by

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

Advanced Java UNit II

Uploaded by

Aditi Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

UNIT – II

Java Swing

Advance Java Programming(22517)

1
Unit Outcomes
 Differentiate between AWT and Swing on given aspect

 Develop GUI Programs using swing components for the

given problem

 Use the given type button in java based GUI

 Develop GUI Programs advanced swing components for the

given problem

2
Topics and Sub-Topics
 Introduction to swing:

 Swing Features, AWT vs Swing

 Swing Components:

 Japplet, Icons and Labels, TextFields, Combo Boxes

 Buttons:

 The JBbutton, Check Boxes, Radio Buttons

 Advanced Swing Components:

 Tabbed Panes, Scroll Panes, Trees, Tables, Progress Bar, Tool Tips

3  MVC Architecture
Introducing Swing
 Although the AWT is still a crucial part of Java, its component set

is no longer widely used to create graphic user interfaces.


Today, most programmers use Swing for this purpose.

 Swing is a set of classes that provides more powerful and

flexible GUI components than does the AWT.

 Simply put, Swing provides the look and feel of the modern

Java GUI.

4
Introducing Swing
 Swing was introduced in a response to deficiencies present in Java’s

original GUI subsystem: the Abstract Window Toolkit.

 The AWT defines a basic set of controls, windows, and dialog boxes that

support a usable, but limited graphical interface.

 One reason for the limited nature of the AWT is that it translates its various

visual components into their corresponding, platform-specific


equivalents, or peers.

 This means that the look and feel of a component is defined by the

platform, not by Java. Because the AWT components use native code
resources, they are referred to as heavyweight.
5
Introducing Swing
 The use of native peers led to several problems.

1. First, because of variations between operating systems, a component


might look, or even act, differently on different platforms. This
potential variability threatened the overarching philosophy of Java:
write once, run anywhere.

2. Second, the look and feel of each component was fixed (because it is
defined by the platform) and could not be (easily) changed.

3. Third, the use of heavyweight components caused some frustrating


restrictions. For example, a heavyweight component is always
rectangular and opaque
6
Introducing 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.

 Swing eliminates a number of the limitations inherent in the AWT, Swing

does not replace it.

 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.
7
Swing Features
 Swing Components Are Lightweight

 With very few exceptions, Swing components are lightweight. This means that

they are written entirely in Java and do not map directly to platform-specific
peers.

 Because lightweight components are rendered using graphics primitives, they

can be transparent, which enables nonrectangular shapes.

 Thus, lightweight components are more efficient and more flexible.

Furthermore, because lightweight components do not translate into native


peers, the look and feel of each component is determined by Swing, not by the
underlying operating system. This means that each component will work in a
consistent manner across all platforms.
8
Swing Features
 Swing supports a pluggable look and feel (PLAF)

 Because each Swing component is rendered by Java code rather than by native

peers, the look and feel of a component is under the control of Swing.

 It is possible to “plug in” a new look and feel for any given component without

creating any side effects in the code that uses that component.

 Pluggable look-and-feels offer several important advantages. It is possible to

define a look and feel that is consistent across all platforms. Conversely, it is
possible to create a look and feel that acts like a specific platform.

 Java SE 6 provides look-and-feels, such as metal and Motif, that are available to

all Swing users. The metal look and feel is also called the Java look and feel. It is
platform-independent and available in all Java execution environments. It is also
9 the default look and feel.
Swing Features
 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.

 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

11 OverlayLayout layout managers.


MVC Architecture
 Software design pattern for software development.
 Model:
 Major function of this layer to maintain the data.
 Database and logic.
 View:
 Used to display full or partial data.
 User Interface
 Controller:
 Control the interaction and communication between Model and
view.
 Communication logic/integration logic

12
MVC Architecture
 Although the MVC architecture and the principles behind it are conceptually

sound,the high level of separation between the view and the controller is not
beneficial for Swing components.

 Instead, Swing uses a modified version of MVC that combines the view and the

controller into a single logical entity called the UI delegate. For this reason, Swing’s
approach is called either the Model-Delegate architecture or the Separable
Model architecture.

 Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.

 Because the view (look) and controller (feel) are separate from the model, the

look and feel can be changed without affecting how the component is used within a

13 program.
Introduction to Swing
 Package : javax.swing.*

 Swing is set of classes which provides more powerful and flexible

components as compare to AWT.

 Build on top of AWT API and acts as replacement of AWT API.

 Swing component follows a Model-View-Controller

 Swing Components are implemented using Java and so they are

platform independent.

 Called lightweight components


14
AWT and Swing Classes

15
AWT: Pros and Cons
 Pros

 Speed: native components speed performance.

 Look and feel: AWT components more closely reflect the look and feel of

the OS they run on.

 Cons

 Portability: use of native peers creates platform specific limitations.

 Features: AWT supports only the lowest common denominator—e.g. no

tool tips or icons.


Swing: Pros and Cons
 Pros

 Portability: Pure Java implementation.

 Features: Not limited by native components.

 Look and Feel: Pluggable look and feel. Components


automatically have the look and feel of the OS their running on.
 Cons

 Performance: Swing components handle their own painting


(instead of using APIs like DirectX on Windows).
 Look and Feel: May look slightly different than native components.
Difference Between AWT & Swing
 AWT uses Applet and Frame while Swing uses JApplet and JFrame for

GUI.

 AWT is platform dependent code while Swing code is platform

independent.

 Swing has bigger collection of classes and interfaces as compare to AWT.

 AWT components are Heavyweight where as Swing components are

Lightweight.

 In Swing extra feature to Button: Provide Image.

 Swing provides: Tree, Table, Scrollpanes, Tabbedpanes, etc. new feature.

18 AWT does not follow MVC.


Components and Container
 A Swing GUI consists of two key items: components and

containers.

 A component is an independent visual control, such as a push

button or slider.

 A container holds a group of components.

 Furthermore, in order for a component to be displayed, it must be

held within a container.

 Thus, all Swing GUIs will have at least one container.


19
Components
 In general, Swing components are derived from the
JComponent class. (The only exceptions to this are the four top-
level containers)

 JComponent supports the pluggable look and feel. JComponent

inherits the AWT classes Container and Component.

 All of Swing’s components are represented by classes defined

within the package javax.swing.

20
Components

21
Containers
 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. Unlike

Swing’s other components, which are lightweight, the top-level containers are
heavyweight.

 A top-level container is not contained within any other container. Furthermore,

every containment hierarchy must begin with a top-level container. The one most
commonly used for applications is JFrame. The one used for applets is JApplet.

22
Containers
 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.

 Lightweight containers are often used to organize and manage groups of related

components because a lightweight container can be contained within another


container.

 Thus, you can use lightweight containers such as JPanel to create subgroups of related

controls that are contained within an outer container

23
The Top-Level Container Panes
 Each top-level container defines a set of panes.

 JRootPane:

 At the top of the hierarchy is an instance of JRootPane.

 JRootPane is a lightweight container whose purpose is to manage the other panes.

 It also helps manage the optional menu bar.

 The panes that comprise the root pane are called the glass pane, the content pane, and

the layered pane.

24
Containers
 Glass pane:
 The glass pane is the top-level pane.

 It sits above and completely covers all other panes.

 By default, it is a transparent instance of JPanel.

 The glass pane enables you to manage mouse events that affect the entire

container (rather than an individual control) or to paint over any other


component, for example.
 In most cases, you won’t need to use the glass pane directly, but it is there if

you need it.

25
Containers
 The layered pane :
 The layered pane allows components to be given a depth value.

 This value determines which component overlays another.

 (Thus, the layered pane lets you specify a Z-order for a component, although this

is not something that you will usually need to do.)

 The layered pane holds the content pane and the (optional) menu bar.

 Although the glass pane and the layered panes are integral to the operation of a

top-level container and serve important purposes, much of what they provide
occurs behind the scene.

26
Containers
 The content pane :
 The pane with which your application will interact the most is the

content pane, because this is the pane to which you will add visual
components.
 In other words, when you add a component, such as a button, to a top-

level container, you will add it to the content pane.


 By default, the content pane is an opaque instance of Jpanel

 getContentPane() method is used to get the content pane object

27
Sample Program

28
New Functionality in Swing
 By default, when a top-level window is closed (such as when the user clicks the

close box), you will usually want the entire application to terminate when its
top-level window is closed.

 The easiest way is to call setDefaultCloseOperation( )

 Syntax: void setDefaultCloseOperation(int what)

 The value passed in what determines what happens when the window is

closed.
 JFrame.EXIT_ON_CLOSE

 JFrame.DISPOSE_ON_CLOSE

 JFrame.HIDE_ON_CLOSE

29
 JFrame.DO_NOTHING_ON_CLOSE
JApplet
 Fundamental to Swing is the JApplet class, which extends Applet.

 Applets that use Swing must be subclasses of JApplet.

 JApplet is rich with functionality that is not found in Applet.

 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


30
Icons
 Icons are specified by objects of type Icon, which is an interface

defined by Swing. The easiest way to obtain an icon is to use the


ImageIcon class.

 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.

31  The second form uses the image in the resource identified by url.
Icons: Methods
 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.


32
Swing labels
 Swing labels are instances of the JLabel class, which extends JComponent.

 It can display text and/or an icon.

 Some of its constructors are shown here:

 JLabel(Icon i)

 JLabel(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 these are constants.


33
Jlabel : Methods
 Icon getIcon( )

 String getText( )

 void setIcon(Icon i)

 void setText(String s)

34
import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet>
*/
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);
}
}
35
Text Fields
 The Swing text field is encapsulated by the JTextComponent class, which extends

JComponent.

 One of its subclasses is JTextField, which allows us to edit one line of text.

 JTextField allows you to edit one line of text, which provides the basic functionality

common to Swing text components.

 JTextField uses the Document interface for its model. Some of its constructors

are shown here:


 JTextField( )

 JTextField(int cols)

 JTextField(String s, int cols)

36  JTextField(String s)
import java.awt.*;
import javax.swing.*;
/* <applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends Japplet {
JTextField jtf;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}}
37
Button
 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 behaviour 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.
38
Methods
 void setDisabledIcon(Icon di)
 void setPressedIcon(Icon pi)
 void setSelectedIcon(Icon si)
 void setRolloverIcon(Icon ri)
 String getText( )
 void setText(String s)
 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.
39
JButton
 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)

40
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="JButtonDemo" width=250 height=300> </applet>
*/
public class JButtonDemo 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);
41
ImageIcon germany = new ImageIcon japan = new
ImageIcon("red.jpg"); ImageIcon("black.jpg");
jb = new JButton(germany); jb = new JButton(japan);
jb.setActionCommand("Red"); jb.setActionCommand("Black");
jb.addActionListener(this);
jb.addActionListener(this); contentPane.add(jb);
contentPane.add(jb); jtf = new JTextField(15);
ImageIcon italy = new contentPane.add(jtf);
ImageIcon("yellow.jpg"); }
jb = new JButton(italy); public void
actionPerformed(ActionEvent ae)
jb.setActionCommand("Yellow");
{
jb.addActionListener(this); jtf.setText(ae.getActionCommand()
contentPane.add(jb); ); }
}

42
43
JCheckBox
 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.
 Some of its constructors are shown here:
 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)

44
 The state of the check box can be changed via the following
method:
 void setSelected(boolean state)
 When a check box is selected or deselected, an item event is
generated. This is handled by itemStateChanged( ).
 Inside itemStateChanged( ), the getItem( ) method gets the
JCheckBox object that generated the event.
 The getText( ) method gets the text for that check box.

45
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JTextField jtf;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JCheckBox cb = new JCheckBox("C", true);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", false);
cb = new JCheckBox("C++", false);
cb.addItemListener(this);
cb.addItemListener(this);
contentPane.add(cb);
contentPane.add(cb); jtf = new JTextField(15);
cb = new JCheckBox("Java", false); contentPane.add(jtf);
cb.addItemListener(this); }
contentPane.add(cb);

46
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}

47
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)

48
 Radio buttons must be configured into a group. Only one of
the buttons in that group can be selected at any time.
 The ButtonGroup class is instantiated to create a button
group. Its default constructor is invoked for this purpose.
 Elements are then added to the button group via the
following method:
 void add(AbstractButton ab)

49
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JTextField tf;
public void init() {
ButtonGroup bg = new
Container contentPane = getContentPane();
ButtonGroup();
contentPane.setLayout(new FlowLayout());
bg.add(b1);
JRadioButton b1 = new JRadioButton("A");
bg.add(b2);
b1.addActionListener(this);
bg.add(b3);
contentPane.add(b1);
tf = new JTextField(5);
JRadioButton b2 = new JRadioButton("B");
contentPane.add(tf);
b2.addActionListener(this);
}
contentPane.add(b2);
public void
actionPerformed(ActionEvent ae)
JRadioButton b3 = new JRadioButton("C"); {
b3.addActionListener(this); tf.setText(ae.getActionCommand(
));
contentPane.add(b3); }
50 }
51
JComboBox
 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. 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.
52
 Items are added to the list of choices via the addItem( ) method:

 void addItem(Object obj)


 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 nmber of rows the JComboBox displays.

 Public void setSelectedItem(Object anObject)


 public void insertItemAt(Object anObject, int index)
 public void removeItem(Object anObject)
 public void removeItemAt(int anIndex)

53
public class JComboBoxDemo extends JApplet
implements ItemListener {
JLabel jl;
ImageIcon green, red, black, yellow;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JComboBox jc = new JComboBox();
jc.addItem("Green");
jc.addItem("Red"); public void
jc.addItem("Black"); itemStateChanged(ItemEvent ie)
{
jc.addItem("Yellow");
String s = (String)ie.getItem();
jc.addItemListener(this); jl.setIcon(new ImageIcon(s + ".jpg"));
contentPane.add(jc); }
jl = new JLabel(new ImageIcon("green.jpg"));}
contentPane.add(jl);
}
54
55
Advanced Swing Components

Advanced Swing Components

56
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.

57
JTabbedPane
 There are three constructors of JTabbedPane.
 JTabbedPane()
 JTabbedPane(int tabPlacement)
 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 :
 JTabbedPane.TOP
 JTabbedPane.BOTTOM
 JTabbedPane.LEFT
 JTabbedPane.RIGHT

58
JTabbedPane
 JTabbedPane(int tabPlacement, int tabLayoutPolicy)

 Tab layout policy may be either of the following:


 JTabbedPane.WRAP_TAB_LAYOUT
 JTabbedPane.SCROLL_TAB_LAYOUT

59
• The general procedure to use a tabbed pane in an applet is
outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this
method define the title of the tab and the component it
contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.

60
 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.

61
import javax.swing.*;
/*<applet code="JTabbedPaneDemo" width=400 height=100> </applet> */
public class JTabbedPaneDemo extends Japplet {
public void init() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Languages", new LangPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}
62
class LangPanel extends JPanel
{
public LangPanel()
{
JButton b1 = new JButton("Marathi");
add(b1);
JButton b2 = new JButton("Hindi");
add(b2);
JButton b3 = new JButton("Bengali");
add(b3);
JButton b4 = new JButton("Tamil");
add(b4);
}
}

63
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}

64
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
65
Scroll Panes
 A scroll pane is a component that presents a rectangular area in
which a component may be viewed.
 Horizontal and/or vertical scroll bars may be provided if
necessary.
 Scroll panes are implemented in Swing by the JScrollPane class,
which extends JComponent.

66
Constructors
 JScrollPane()
 JScrollPane(Component comp)
 JScrollPane(int vsb, int hsb)
 JScrollPane(Component comp, int vsb, int hsb)
 Here, comp is component to add 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.
 HORIZONTAL_SCROLLBAR_ALWAYS
 HORIZONTAL_SCROLLBAR_AS_NEEDED
 VERTICAL_SCROLLBAR_ALWAYS
 VERTICAL_SCROLLBAR_AS_NEEDED
67
• Here are the steps that you should follow to use a scroll pane
in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the
constructor specify the component and the policies for
vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.

68
public class JScrollPaneDemo extends Japplet {
public void init(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b; } }
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
}}

69
70
Trees
 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.

71
JTree
• Trees are implemented in Swing by JTree class, which extends
JComponent.
• 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 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.

72
 A JTree object generates events when a node is expanded or collapsed. The
following methods allow listeners to register and unregister for these
notifications.
 void addTreeExpansionListener(TreeExpansionListener tel)
 void removeTreeExpansionListener(TreeExpansionListener tel)
 Here, tel is the listener object.
 The getPathForLocation( ) method is used to translate a mouse click on a
specific point of the tree to a tree path.
 TreePath getPathForLocation(int x, int y)
 Here, x and y are the coordinates at which the mouse is clicked.
 The return value is a TreePath object that encapsulates information about
the tree node that was selected by the user.

73
 The TreePath class encapsulates information about a path to a particular
node in a tree. It provides several constructors and methods.
 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.

74
 The DefaultMutableTreeNode class implements the
MutableTreeNode interface.
 It represents a node in a tree.
 DefaultMutableTreeNode(Object obj)
 Here, obj is the object to be enclosed in this tree node.
 The new tree node doesn’t have a parent or children.
 To create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used.
 void add(MutableTreeNode child)

75
 Tree expansion events are described by the class TreeExpansionEvent in
 the javax.swing.event package.
 The getPath( ) method of this class returns a TreePath object that
describes the path to the changed node.
 TreePath getPath( )
 The TreeExpansionListener interface provides the following two
methods:
 void treeCollapsed(TreeExpansionEvent tee)
 void treeExpanded(TreeExpansionEvent tee)
 Here, tee is the tree expansion event.
 The first method is called when a sub-tree is hidden, and the second
method is called when a sub-tree becomes visible.
76
• Here are the steps that we should follow to use a tree in an
applet:
1. Create a JTree object.
2. Create a JScrollPane object. (The arguments to the constructor
specify the tree and the policies for vertical and horizontal
scroll bars.)
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane of the applet.

77
78
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/* <applet code="JTreeEvents" width=400 height=200>
</applet>
*/
public class JTreeEvents extends JApplet
{
JTree tree;
JTextField jtf;
public void init()
{
79
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);

80
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);
}
});
}

81
void doMouseClicked(MouseEvent me)
{
TreePath p=tree.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}

82
Tables

 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. One of its constructors is shown here:
 JTable(Object data[ ][ ], Object colHeads[ ])
 JTable(int numRows, int numColumns)
 JTable(Vector rowData, Vector columnData)

83
• 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.

84
import java.awt.*;
import javax.swing.*;
/* <applet code="JTableDemo" width=400 height=200>
</applet> */
public class JTableDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
final String[] colHeads = { "Name", "Phone", "Fax" };
final Object[][] data = {

85
{ "Pramod", "4567", "8675" },
{ "Tausif", "7566", "5555" },
{ "Nitin", "5634", "5887" },
{ "Amol", "7345", "9222" },
{ "Vijai", "1237", "3333" },
{ "Ranie", "5656", "3144" },
{ "Mangesh", "5672", "2176" },
};
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);
}
}

86
87
JProgressBar
 JProgressBar visually displays the progress of some specified task.
 JProgressBar shows the percentage of completion of specified task.
 The progress bar fills up as the task reaches it completion.
 In addition to show the percentage of completion of task, it can also
display some text .
 Constructors of JProgressBar :
 JProgressBar() : creates an progress bar with no text on it;
 JProgressBar(int orientation) orientation -
SwingConstants.VERTICAL, SwingConstants.HORIZONTAL
 JProgressBar(int min, int max)
 JProgressBar(int orientation, int min, int max)

88
 methods of JProgressBar are :
 int getMaximum() : returns the progress bar’s maximum value.
 int getMinimum() : returns the progress bar’s minimum value.
 String getString() : get the progress bar’s string representation of
current value.
 void setMaximum(int n) : sets the progress bar’s maximum value
to the value n.
 void setMinimum(int n) : sets the progress bar’s minimum value to
the value n.
 void setValue(int n) : set Progress bar’s current value to the value n.
 void setString(String s) : set the value of the progress String to the
String s.

89
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class progress extends JFrame {
static JFrame f;
static JProgressBar b;
public static void main()
{
f = new JFrame("ProgressBar demo");
JPanel p = new JPanel();
b = new JProgressBar();
b.setValue(0);

90
b.setStringPainted(true);
p.add(b);
f.add(p);
f.setSize(500, 500);
f.setVisible(true);
fill();
}
public static void fill() {
int i = 0;
try {
while (i <= 100) {
b.setValue(i + 10);
Thread.sleep(1000);
i += 20;
} } catch (Exception e) {
} } }
91

You might also like