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

Swing Features and Components

Swing is a GUI widget toolkit for Java that replaces AWT. It provides platform-independent components like trees, tables, tabbed panes and sliders. Swing components are lightweight and follow the MVC architecture. Common Swing components include JButton, JTextField, JComboBox, JProgressBar, JPanel, JScrollPane, JTable and JTabbedPane.

Uploaded by

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

Swing Features and Components

Swing is a GUI widget toolkit for Java that replaces AWT. It provides platform-independent components like trees, tables, tabbed panes and sliders. Swing components are lightweight and follow the MVC architecture. Common Swing components include JButton, JTextField, JComboBox, JProgressBar, JPanel, JScrollPane, JTable and JTabbedPane.

Uploaded by

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

Introduction to Swing

Swing API is set of extensible GUI


Components to create JAVA based Front End/
GUI Applications. It is build upon top of AWT
API and acts as replacement of AWT API as it
has almost every control corresponding to
AWT controls.
Swing Features
➢Light Weight - Swing component are
independent of native Operating System's API as
Swing API controls are rendered mostly using
pure JAVA code instead of underlying operating
system calls.
➢Rich controls - Swing provides a rich set of
advanced controls like Tree, TabbedPane, slider,
colorpicker, table controls
➢Pluggable look-and-feel- SWING based GUI
Application look and feel can be changed at run
time based on available values.
Difference between AWT and Swing
N Java AWT Java Swing
o.

1 AWT components are platform- Java swing components


dependent. are platform-independent.

2 AWT components are heavyweight. Swing components are lightweight.

3 AWT doesn't support pluggable Swing supports pluggable look


look and feel. and feel.

4 AWT provides less Swing provides more powerful


components than Swing. componentssuch as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5 AWT doesn't follows MVC(Model Swing follows MVC.


View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
MVC Architecture
Swing API architecture follows MVC
architecture. The MVC design pattern consists
of three modules: model, view and controller.
Model -The model represents the state (data) and
business logic of the application.
View -The view module is responsible to display data
i.e. it represents the presentation.
Controller -The controller module acts as an
interface between view and model. It intercepts all
the requests i.e. receives input and commands to
Model / View to change accordingly.
Figure: MVC Architecture
JComboBox
Combo box is a combination of text fields and
drop-down list.JComboBox component is used
to create a combo box in Swing.

Constructor for JComboBox


JComboBox()
JComboBox(String arr[])
Methods used with JComboBox
• void addItem(Object anObject)
– Adds an item to the item list.
• void addItemListener(ItemListener aListener)
– Adds an ItemListener.
• Object getItemAt(int index)
– Returns the list item at the specified index.
• int getItemCount()
– Returns the number of items in the list.
• Object getSelectedItem()
– Returns the current selected item.
• void removeAllItems()
– Removes all items from the item list.
• void removeItem(Object anObject)
– Removes an item from the item list.
• void removeItemAt(int anIndex)
– Removes the item at anIndex This method works only if the JComboBox uses a
mutable data model.
import javax.swing.*;
public class JComboTest
{
JFrame f;
JComboTest()
{
f=new JFrame("Combo ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JComboTest();
}
}
JProgressBar
The class JProgressBar is a component which
visually displays the progress of some task.
Constructors of JProgessBar
➢ JProgressBar()
Creates a horizontal progress bar that displays a
border but no progress string.
➢ JProgressBar(int orient)
Creates a progress bar with the specified
orientation, which can be either SwingConstants.
VERTICAL or SwingConstants.HORIZONTAL.
➢ JProgressBar(int min, int max)
Creates a horizontal progress bar with the
specified minimum and maximum values.
➢ JProgressBar(int orient, int min, int max)
Creates a progress bar using the specified
orientation, minimum and maximum values.
Methods used with JProgressBar
• void setStringPainted(boolean b)
– determines whether the progress bar should display a
progress string.
• int getMaximum()
– Returns the progress bar's maximum value
• int getMinimum()
– Returns the progress bar's minimum value from the
BoundedRangeModel.
• int getOrientation()
– Returns SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL, depending on the
orientation of the progress bar.
import javax.swing.*; public void iterate()
public class MyProgress extends Jframe {
{ while(i<=2000)
JProgressBar jb; {
int i=0,num=0; jb.setValue(i);
i=i+20;
MyProgress() try
{ {
jb=new JProgressBar(0,2000); Thread.sleep(150);
jb.setBounds(40,40,200,30); }
catch(Exception e){}
jb.setValue(0); }
jb.setStringPainted(true); }
public static void main(String[] args)
add(jb); {
setSize(400,400); MyProgress m=new MyProgress();
setLayout(null); m.setVisible(true);
} m.iterate();
setDefaultCloseOperation(JFrame.EXIT_ON_ }
CLOSE); }
JPanel
A panel is a swing container which is used
for grouping components which is later on
added to the frame. In java swing panel is
implemented by JPanel class.
Constructors of JPanel
➢JPanel()
Creates a panel.
➢JPanel(LayoutManager)
The LayoutManager parameter provides a
layout manager for the new panel. By default,
a panel uses a FlowLayout to lay out its
components.
import javax.swing.*;
import java.io.*;
class B
{
public static void main(String arg[])
{
JFrame f=new JFrame("this is my new frame");
JPanel p=new JPanel();
f.add(p);
f.setSize(200,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JScrollPane

A JScrollPane provides a scrollable view of a


component. When screen real estate is
limited, use a scroll pane to display a
component that is large or one whose size can
change dynamically. i.e. It represents a
scrollpane which is a rectangular area in which
a component may be viewed.
Constructors of JScrollPane
JScrollPane()
Create a scroll pane
JScrollPane(Component com)
com is component which is added to scroll
pane.
JScrollPane(int vsb, int hsb)
vasb and hsb are int constants for controlling
vertical and horizontal scrolling.
JScrollPane(Component com, int vsb, int hsb)
int constants vsb nad hsb can have the values:

• VERTICAL_SCROLLBAR_ALWAYS
– Vertical scroll bar is always provided.
• HORIZONTAL_SCROLLBAR_ALWAYS
– Horizontal scroll bar is always provided.
• VERTICAL_SCROLLBAR_AS_NEEDED
– Vertical scroll bar is provided as per the need.
• HORIZONTAL_SCROLLBAR_AS_NEEDED
– Horizontal scroll bar is provided as per the need.
import javax.swing.*;
import java.awt.event.*;
public class scroll {
public static void main(String[] args) {
String s="Welcome to Java Swing programming!!!!! This shows the working of
JScrollPane.....";
JTextArea t=new JTextArea(s,10,10);
JFrame f=new JFrame("Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane sp=new JScrollPane(t,v,h);
p.add(sp);
f.add(p);
f.setSize(200,200);
f.setVisible(true);
}
}
JTable
The JTable class is used to display the data on
two dimensional tables of cells.

Constructors of JTable class:


➢JTable()
creates a table with empty cells.
➢JTable(Object[][] rows, Object[] columns)
creates a table with the specified data.
import javax.swing.*;
public class MyJTable extends JFrame {
MyJTable()
{
String data[][]={
{"101","Umesh","670000"},
{"102","Vijay","780000"},
{"101","Rahul","700000"}};
String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);


jt.setBounds(30,40,200,300);

JScrollPane sp=new JScrollPane(jt);


add(sp);

setSize(300,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyJTable();
}
}
JTabbedPane
JTabbedPane is a container component that
lets the user switch between pages by clicking
on a tab.
Constructors for JTabbedPane
➢ JTabbedPane()
Creates an empty TabbedPane with a default tab
placement of JTabbedPane.TOP.
➢ JTabbedPane(int tabPlacement)
Creates an empty TabbedPane with the specified
tab placement of either: JTabbedPane.TOP,
JTabbedPane.BOTTOM, JTabbedPane.LEFT, or
JTabbedPane.RIGHT.
➢ JTabbedPane(int tabPlacement, int tabLayoutPolicy)
Creates an empty TabbedPane with the specified
tab placement and tab layout policy.
import javax.swing.*;
/* <applet code="exp43" width=400 height=100> </applet> */

public class exp43 extends JApplet


{
public void init()
{
JTabbedPane exp43 = new JTabbedPane();
exp43.addTab("Cities", new CitiesPanel());
exp43.addTab("Colors", new ColorsPanel());
exp43.addTab("Flavors", new FlavorsPanel());
add(exp43);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("Kolhapur");
add(b1);
JButton b2 = new JButton("Karad");
add(b2);
JButton b3 = new JButton("Satara");
add(b3);
JButton b4 = new JButton("Pune");
add(b4);
}
}
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);
}
}

class FlavorsPanel extends JPanel


{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
JTree
JTree class is a powerful Swing component for
displaying tree-structured data.
A JTree object does not actually contain your data; it
simply provides a view of the data. Like any non-
trivial Swing component, the tree gets data by
querying its data model. Here is a picture of a tree:
➢Each row displayed by the tree contains
exactly one item of data, which is called
a node.
➢ Every tree has a root node from which all
nodes descend.
➢A node can either have children or not.
➢We refer to nodes that can have children
as branch nodes. Nodes that can not have
children are leaf nodes.
➢Branch nodes can have any number of
children.
➢A specific node in a tree can be identified
either by a TreePath, an object that
encapsulates information about the node, or
by its display row, where each row in the
display area displays one node.
➢An expanded node is a non-leaf node that will
display its children when all its ancestors are
expanded.
➢A collapsed node is one which hides them.
➢A hidden node is one which is under a
collapsed ancestor.
Constructors Of JTree
• JTree(Hashtable ht)
– Returns a JTree created from a Hashtable which does not
display with root. Each element of hashtable is a childnode.
• JTree(Object[] value)
– Returns a JTree with each element of the specified array as
the child of a new root node which is not displayed. Each
element of the array object is childnode.
• JTree(TreeNode root)
– Returns a JTree with the specified TreeNode as its root, which
displays the root node. Treenode tn is the root of the tree.
• JTree(Vector v)
– Returns a JTree with each element of the specified Vector as
the child of a new root node which is not displayed. Elements
of vector v is the childnode
• It is possible to obtain a reference to the
parent node.
• The ‘MutableTreeNode’ interface extends
‘TreeNode’, which is an interface that declares
methods that obtain information about a tree
node.
• The ‘DefaultMutableTreeNode’ class
implements the ‘MutableTreeNode’ interface.
It represents a node in a tree.
Methods used with JTree
DefaultMutableTreeNode(object obj)
where ‘obj’ is the object to be enclosed in this
tree node.
void add(MutableTreeNode child)
This method can be used to create the hierarchy
of nodes .where ‘child’ is the mutable treenode
this is to be added as a child to the current node.
TreePath getPathForLocation(int x, int y)
It is used to translate a mouse click on a point of
tree to a tree path. Where, x and y are
coordinates of mouse click.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class tree
{
public static void main(String[] args)
{
wood o=new wood();
o.wod();
}
}
class wood extends JFrame
{
public void wod()
{
JFrame f=new JFrame();
DefaultMutableTreeNode root=new DefaultMutableTreeNode("Asia");
DefaultMutableTreeNode country=new
DefaultMutableTreeNode("India");
DefaultMutableTreeNode state=new DefaultMutableTreeNode("Madhya
Pradesh");
DefaultMutableTreeNode city=new DefaultMutableTreeNode("Gwalior");
root.add(country);
country.add(state);
state.add(city);
JTree tree=new JTree(root);
f.add(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
f.setVisible(true);
}
}
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonWithTooltip extends Jframe
{
public JButtonWithTooltip()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
b.setToolTipText("Help text for the button");
getContentPane().add(b, "Center");
pack();
}
public static void main(String[] args)
{
new JButtonWithTooltip().setVisible(true);
}
}
ToolTip
Tooltip text is normally one line long. The
setToolTipText() method from JComponent
used to create a tooltip.

public void setToolTipText(String text)


-Registers the text to display in a tool tip.
The text displays when the cursor lingers over
the component.
JSeparators
➢ The JSeparator class provides a horizontal or
vertical dividing line or empty space. It's most
commonly used in menus and tool bars.
➢ Separators are similar to borders, except that
they are genuine components and are drawn
inside a container, rather than around the edges
of a particular component.
➢ Menus and tool bars provide convenience
methods that create and add separators
customized for their containers.
menu.addSeparator();
Consrtuctors for JSeparators
➢JSeparator()
Create a separator. If you don't specify an
argument, the separator is horizontal.
➢JSeparator(int)
The argument can be either
SwingConstants.HORIZONTAL or
SwingConstants.VERTICAL.
import javax.swing.*;
public class MenuSeparator extends Jframe
{
public MenuSeparator()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
bar.add(menu);
menu.add(new JMenuItem("Close"));
menu.add(new JSeparator()); // SEPARATOR
menu.add(new JMenuItem("Exit"));
setJMenuBar(bar);
getContentPane().add(new JLabel("A placeholder"));
setSize(300, 300);
setVisible(true);
}
public static void main(String arg[])
{
new MenuSeparator();
}
}
import java.awt.*;
import javax.swing.*;
public class AnotherSeparatorSample
{
public static void main(String args[])
{
JFrame f = new JFrame("JSeparator Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new GridLayout(0, 1));
JLabel above = new JLabel("Above Separator");
content.add(above);
JSeparator separator = new JSeparator();
content.add(separator);
JLabel below = new JLabel("Below Separator");
content.add(below);
f.setSize(300, 100);
f.setVisible(true);
}
}
JToggleButton
A toggle button is two-states button that allows
user to switch on and off. To create a toggle
button JToggleButton class is used.
Constructors for JToggleButton
➢JToggleButton( )
Creates a toggle button without text and icon.
The state of toggle button is not selected.
➢JToggleButton(String text)
Creates a toggle button with text
➢JToggleButton(String text, boolean selected)
Creates a toggle button with text and
initialize the state of the toggle button
import java.awt.*;
import javax.swing.*;
public class ToggleButtonSample
{
public static void main(String args[])
{
JFrame f = new JFrame("JToggleButton Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.add(new JToggleButton("North"), BorderLayout.NORTH);
content.add(new JToggleButton("East"), BorderLayout.EAST);
content.add(new JToggleButton("West"), BorderLayout.WEST);
content.add(new JToggleButton("Center"),BorderLayout.CENTER);
content.add(new JToggleButton("South"), BorderLayout.SOUTH);
f.setSize(300, 200);
f.setVisible(true);
}
}
Using Top-Level Containers
➢ Swing provides three generally useful top-level container

classes: JFrame, JDialog, and JApplet.

➢ A container has several layers in it. You can think of a layer as a

transparent film that overlays the container.

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


getContentPane()
Returns the contentPane object for this
container.
import java.awt.*;
import java.applet.*;
import javax.swing.*;
public class GridLayoutExample extends JApplet
{
public void init()
{
Container c = getContentPane();
c.setLayout(new GridLayout(2, 4));
c.add(new JButton("One"));
c.add(new JButton("Two"));
c.add(new JButton("Three"));
c.add(new JButton("Four"));
c.add(new JButton("Five"));
}
}
import java.awt.*;
import javax.swing.*;
public class Frame4a
{
public static void main(String[] args)
{
JFrame f = new JFrame("JFrame with a JPanel");
JLabel L = new JLabel("Hello World !");
JPanel P = new JPanel(); // Make a Jpanel
P.add(L);
f.getContentPane().add(P);
f.setSize(400,300);
f.setVisible(true);
}
}

You might also like