Unit Five
Unit Five
Swings:
AWT is used for creating GUI in Java. However, the AWT components are internally
depends on native methods like C functions and operating system equivalent and hence
problems related to portability arise (look and feel. Ex. Windows window and MAC
window). And, also AWT components are heavy weight. It means AWT components take
more system resources like memory and processor time.
Due to this, Java soft people felt it is better to redevelop AWT package without
internally taking the help of native methods. Hence all the classes of AWT are extended to
form new classes and a new class library is created. This library is called JFC (Java
Foundation Classes).
JFC is an extension of original AWT. It contains classes that are completely portable,
since the entire JFC is developed in pure Java. Some of the features of JFC are:
So, JFC represents class library developed in pure Java which is an extension to AWT and
swing is one package in JFC, which helps to develop GUIs and the name of the package is
import javax.swing.*;
Here x represents that it is an ‘extended package’ whose classes are derived from
AWT package.
MVC Architecture:
In MVC terminology,
Model corresponds to the state information associated
with the component (data).
For example, in the case of a check box, the model
contains a field that indicates if the box is checked
or unchecked.
The view visual appearance of the component based
upon model data.
Unit 5 Introduction to Swings & Networking
The controller 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.
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.
Figure : With Swing, the view and the controller are combined into a UI-delegate object
So let’s review: each Swing component contains a model and a UI delegate. The
model is responsible for maintaining information about the component’s state. The UI
delegate is responsible for maintaining information about how to draw the component on the
screen. In addition, the UI delegate reacts to various events.
AWT Swing
Heavy weight Light weight
Look and feel is OS based Look and feel is OS independent.
Not pure Java based Pure Java based
Applet portability: Web-browser is support Applet portability: A plug-in is
required
Do not support features like icon and tool It supports.
tip.
The default layout manager for applet: The default layout manger for content
flow and frame is border layout. pane is border layout.
2
Unit 5 Introduction to Swings & Networking
Components and Containers:
Components:
In general, Swing components are derived from the JComponent class. JComponent
provides the functionality that is common to all components. For example, 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. The following figure shows hierarchy of classes of javax.swing.
3
.
Unit 5 Introduction to Swings & Networking
Containers:
Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane. To
reach this glass pane we use getGlassPane() method of JFrame class, which return
Component class object.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame. To go to the root pane, we can use
getRootPane() method of JFrame class, which returns JRootPane object.
Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane. We can reach this
pane by calling getLayeredPane() method of JFrame class which returns
JLayeredPane class object.
Conent pane: This is bottom most of all, Individual components are attached to this
pane. To reach this pane, we can call getContentPane() method of JFrame class
which returns Container class object.
4
Unit 5 Introduction to Swings & Networking
JFrame:
We know frame represents a window with a title bar and borders. Frame becomes the
basis for creating the GUIs for an application because all the components go into the frame.
To create a fram, we have to create an object to JFrame class in swing as
JFrame jf=new JFrame(); // create a frame without title
JFrame jf=new JFrame(“title”); // create a frame with title
To close the frame, use setDefaultCloseOperation() method of JFrame class
setDefaultCloseOperation(constant)
where constant values are
This closes the application upon clicking the
JFrame.EXIT_ON_CLOSE
close button
This closes the application upon clicking the
JFrame.DISPOSE_ON_CLOSE
close button
This will not perform any operation upon
JFrame.DO_NOTHING_ON_CLOSE clicking close button
This hides the frame upon clicking close
JFrame.HIDE_ON_CLOSE
button
Example:
import javax.swing.*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE );
}
}
Example: To set the background
import javax.swing.*;
import java.awt.*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
Container c=jf.getContentPane();
c.setBackground(Color.green);
}
}
5
Unit 5 Introduction to Swings & Networking
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.
One difference between Applet and JApplet is, 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( )
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.
JComponent:
The class JComponent is the base class for all Swing components except top-level
containers. To use a component that inherits from JComponent, you must place the
component in a containment hierarchy whose root is a top-level SWING container.
Constructor: JComponent();
The following are the JComponent class's methods to manipulate the appearance of
the component.
Returns the current width of this component
public int getWidth ()
in pixel.
Returns the current height of this component
public int getHeight ()
in pixel.
Returns the current x coordinate of the
public int getX()
component's top-left corner.
Returns the current y coordinate of the
public int getY ()
component's top-left corner.
Returns this component's Graphics object
public java.awt.Graphics getGraphics() you can draw on. This is useful if you want
to change the appearance of a component.
public void setBackground (java.awt.Color bg) Sets this component's background color.
Sets whether or not this component is
public void setEnabled (boolean enabled)
enabled.
Set the font used to print text on this
public void setFont (java.awt.Font font)
component.
public void setForeground (java.awt.Color fg) Set this component's foreground color.
public void setToolTipText(java.lang.String text) Sets the tool tip text.
Sets whether or not this component is
public void setVisible (boolean visible)
visible.
6
Unit 5 Introduction to Swings & Networking
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 you 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.
The following example illustrates how to create a text field. The applet begins by
getting its content pane, and then a flow layout is assigned as its layout manager. Next, a
JTextField object is created and is added to the content pane.
Example:
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content
pane jtf = new JTextField(10);
contentPane.add(jtf);
}
}
Check Boxes:
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate super class is JToggleButton, which
provides support for two-state buttons (true or false). 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)
Here, i is the icon for the button. The text is specified by s. If state is true, the check
box is initially selected. Otherwise, it is not.
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
8
Unit 5 Introduction to Swings & Networking
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 and uses it to set the text inside the text field.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo2" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo2 extends JApplet implements ItemListener
{
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
cb = new JCheckBox("C++");
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
contentPane.add(cb);
9
Unit 5 Introduction to Swings & Networking
Radio Buttons:
Radio buttons are supported by the JRadioButton class, which is a concrete
implementation of AbstractButton. Its immediate superclass 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)
Here, i is the icon for the button. The text is specified by s. If state is true, the
button is initially selected. Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. For example, if a user presses a radio button that is in a group,
any previously selected button in that group is automatically deselected. 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)
Here, ab is a reference to the button to be added to the group.
Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method gets the text that is associated with a radio button and
uses it to set the text field.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet implements ActionListener
{
JTextField tf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
10
Unit 5 Introduction to Swings & Networking
JRadioButton cpp = new JRadioButton("C++");
cpp.addActionListener(this);
contentPane.add(cpp);
}
public void actionPerformed(ActionEvent ae)
{ tf.setText(ae.getActionCommand());
}
}
Combo boxes:
Swing provides a combo box (a combination of a text field and a drop-down 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. You can also type your selection into the text
field.
Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box. 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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet implements ItemListener
{
Container contentPane;
jc.addItemListener(this);
contentPane.add(jc);
}
public void itemStateChanged(ItemEvent ie)
{
String s = (String)ie.getItem();
JOptionPane.showMessageDialog(null,"You selected:"+s);
}
}
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. We will use its default constructor. 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.
12
Unit 5 Introduction to Swings & Networking
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.
The following example illustrates how to create a tabbed pane. The first tab is
titled“Cities” and contains four buttons. Each button displays the name of a city. The second
tab is titled “Colors” and contains three check boxes. Each check box displays the name of a
color. The third tab is titled “Language” and contains radio buttons.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400
height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Language", new LanguagesPanel());
contentPane.add(jtp);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("Amaravati");
add(b1);
JButton b2 = new JButton("Hyderabad");
add(b2);
JButton b3 = new JButton("Vijayawada");
add(b3);
JButton b4 = new JButton("Tirupati");
13
Unit 5 Introduction to Swings & Networking
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 LanguagesPanel extends JPanel
{
public LanguagesPanel()
{
JRadioButton rb1 = new JRadioButton("Telugu");
add(rb1);
JRadioButton rb2 = new JRadioButton("Hindi");
add(rb2);
JRadioButton rb3 = new JRadioButton("English");
add(rb3);
}
}
JLabel :
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel
can display text, image or both . JLabel is only a display of text or image and it cannot get focus
. JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are
vertically centered but the user can change the alignment of label.
JList :
JList is part of Java Swing package . JList is a component that displays a set of Objects and
allows the user to select one or more items . JList inherits JComponent class. JList is a easy way
to display an array of Vectors .
method explanation
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
//frame
static JFrame f;
//lists
static JList b;
//main class
public static void main(String[] args)
{
//create a new frame
f = new JFrame("frame");
//create a object
solve s=new solve();
//create a panel
JPanel p =new JPanel();
//create list
b= new JList(week);
f.add(p);
f.show();
}
APPLETS
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.
The Applet class is contained in the java.applet package.Applet contains several methods
that give you detailed control over the execution of your applet.
Applet Basics:
All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must
also import java.awt. AWT stands for the Abstract Window Toolkit. Since all applets run in a
window, it is necessary to include support for that window by importing java.awt package.
Applets are not executed by the console-based Java run-time interpreter. Rather, they are
executed by either a Web browser or an applet viewer.
Execution of an applet does not begin at main( ). Output to your applet’s window is
not performed by System.out.println( ). Rather, it is handled with various AWT methods,
such as drawString( ), which outputs a string to a specified X,Y location. Input is also
handled differently than in an application.
Once an applet has been compiled, it is included in an HTML file using theAPPLET tag. The
applet will be executed by a Java-enabled web browser when it encounters the APPLET tag
within the HTML file.
To view and test an applet more conveniently, simply include a comment at the head of your
Java source code file that contains the APPLET tag.
Applet extends the AWT class Panel. In turn, Panel extends Container, which
extends Component. These classes provide support for Java’s window-based, graphical
interface. Thus, Applet provides all of the necessary support for window-based activities
Applet Architecture:
An applet is a window-based program. As such, its architecture is different from the so-called
normal, console-based programs .
First, applets are event driven. it is important to understand in a general way how the event-
driven architecture impacts the design of an applet.
Here is how the process works. An applet waits until an event occurs. The AWT notifies the
applet about an event by calling an event handler that has been provided by the applet. Once
this happens, the applet must take appropriate action and then quickly return control to the
AWT.
It is important to understand the order in which the various methods shown in theskeleton are
called. When an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( ):init( ) method is called once—the first time an applet is loaded. The init( ) method is
the first method to be called. This is where you should initialize variables.
start():The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped(i.e start() method is called every time, the applet resumes execution).
Paint():The paint( ) method is called each time your applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is
running may be overwritten by another window and then uncovered. Or the applet window
may be minimized and then restored. paint( ) is also called when the applet begins execution.
Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The
paint( ) method has one parameter of type Graphics.
stop( ):The stop() method is called when the applet is stopped(i.e for example ,when
the applet is minimized the stop method is called).
destroy( ):The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory(i.e destroy() method is called when the applet
is about to terminate).The stop( ) method is always called before destroy( ).
An Applet Skeleton
Program:
SimpleApplet.java
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=300 height=100>
</applet>
*/
g.drawString(msg,20,20);
}
}
Output:
How To Run an Applet Programe:
SimpleApplet.html
<html>
<body>
<applet code="SimpleApplet" width=300 height=100></applet>
</body>
</html>
As we’ve mentioned, applets are displayed in a window and they use the AWT to perform
input and output.To output a string to an applet, use drawString( ), which is a member of the
Graphics class.Graphics class is defined in java.awt package.
Here, message is the string to be output and x and y are x-coordinate ,y-coordinate
respectively. In a Java window, the upper-left corner is location 0,0.
To set the background color of an applet’s window, use setBackground( ). To set the
foreground color (the color in which text is shown, for example), use setForeground( ).
These methods are defined by Component, and they have the following general forms:
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
For example, this sets the background color to green and the text color to red:
setBackground(Color.green);
setForeground(Color.red);
Sample.java
/* A simple applet that sets the foreground and background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=200>
</applet>*/
public class Sample extends Applet
{
String msg;
public void init()
{
setBackground(Color.gray);
setForeground(Color.white);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{ msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
Output :
Requesting Repainting:
Whenever your applet needs to update the information displayed in its window, it
simply calls repaint( ).The repaint( ) method is defined by the AWT. It causes the AWT
run-time system to execute a call to your applet’s update( ) method, which,
in its default implementation, calls paint( ).
There are two varieties of applets. The first are those based directly on the Applet
class. These applets use the Abstract Window Toolkit (AWT) to provide the graphic user
interface (or use no GUI at all). This style of applet has been available since Java was first
created.
The second type of applets are those based on the Swing class JApplet. Swing applets use
the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use
user interface than does the AWT. Thus, Swing-based applets are now the most popular.
JApplet inherits Applet, all the features of Applet are also available in Japplet.
Web pages can contain two types of applets which are named after the location at which they
are stored.
1. Local Applet 2. Remote Applet
Local Applets: A local applet is the one that is stored on our own computer system. When
the Web-page has to find a local applet, it doesn't need to retrieve information from the
Internet. A local applet is specified by a path name and a file name as shown below in which
the codebase attribute specifies a path name, whereas the code attribute specifies the name of
the byte-code file that contains the applet's code.
Remote Applets: A remote applet is the one that is located on a remote computer system .
This computer system may be located in the building next door or it may be on the other side
of the world. No matter where the remote applet is located, it's downloaded onto our
computer via the Internet. The browser must be connected to the Internet at the time it needs
to display the remote applet. To reference a remote applet in Web page, we must know the
applet's URL (where it's located on the Web) and any attributes and parameters that we need
to supply. A local applet is specified by a url and a file name as shown below.