OOP thr Java-UNIT 5
OOP thr Java-UNIT 5
UNIT – V
Applets – Concepts of Applets, differences between applets and applications, life cycle of
an applet, types of applets, creating applets, passing parameters to applets. Swing –
Introduction, limitations of AWT, MVC architecture, components, containers, exploring
swing- JApplet, JFrame and JComponent, Icons and Labels, text fields, buttons – The
JButton class, Check boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes,
Trees, and Tables.
The AWT contains window-based, graphical user interface. The paint( ) method has
one parameter of type Graphics. Inside paint( ) is a call to drawString( ), which is a
member of the Graphics class. This method outputs a string beginning at the specified
X, Y location.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms, including Linux,
Windows, Mac OS etc.
C:\Users\Admin>JAVAC
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
Java Application: Java Application is just like a Java program that runs on an
underlying operating system with the support of a virtual machine. It is also known as
an application program. The graphical user interface is not necessary to execute the java
applications; it can be run with or without it.
Java Applet: An applet is a Java program that can be embedded into a web page. It
runs inside the web browser and works at client side. An applet is embedded in an
HTML page using the APPLET or OBJECT tag and hosted on a web server. Applets are
used to make the web site more dynamic and entertaining.
Types of applets
Creating applets
For creating any applet java.applet.Applet class must be inherited. It provides life
cycle methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
public void paint(): ) is called each time your applet’s output must be redrawn.
It is also called when the applet begins execution.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
import java.awt.*;
import java.applet.*;
<html>
<body>
Here is the output of my program:
<applet code="SimpleApplet.class" width="250" height="200"></applet>
</body>
</html>
OUTPUT:
D:\Java>javac SimpleApplet.java
D:\Java>appletviewer Applet.html
import java.awt.*;
import java.applet.*;
public class SimpleExample extends Applet
{
String msg="";
public void init()
{
msg="Hello Java ";
}
public void start()
{
msg=msg+" Welcome to Applet";
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
Font f=new Font("verdana", Font.BOLD, 12);
g.setFont(f);
g.drawString(msg,20,30);
}
}
/*
<applet code="SimpleExample" width=250 height=200>
</applet>
*/
OUTPUT:
D:\Java>javac SimpleExample.java
D:\Java>appletviewer SimpleExample.java
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
import java.applet.Applet;
import java.awt.Graphics;
<html>
<body>
<applet code="UseParam.class" width="300" height="100">
<param name="msg" value="Welcome to Applet in Java ">
</applet>
</body>
</html>
OUTPUT:
D:\Java> javac UseParam.java
D:\Java> appletviewer UseParam.html
Swing – Introduction
Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI
components. Swing provides a rich set of widgets and packages to make sophisticated
GUI components for Java applications. Swing is a part of Java Foundation Classes
(JFC), which is an API for Java programs that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an
older, platform dependent GUI toolkit. You can use the Java GUI programming
components like button, textbox, etc. from the library and do not have to create the
components from scratch.
Dialog: It can be thought of like a pop-up window that pops out when a message
has to be displayed. It is not a fully functioning window like the Frame.
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for
Java applications. It is mainly made of graphical components like buttons, labels,
windows, etc. through which the user can interact with an application. GUI plays an
important role to build easy interfaces for Java applications.
import javax.swing.*;
class Gui
{
public static void main(String args[])
{
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}
OUTPUT:
D:\Java>javac Gui.java
D:\Java>java Gui
Import javax.swing.*;
public class SwingDemo
{
public static void main(String[] args)
{
//creating instance of JFrame
JFrame f=new JFrame("Swing Creation");
Limitations of AWT
AWT has limited GUI components; components like table, tree, progress bar
cannot be supported by AWT.
Although AWT is thread-safe, it slows down the running speed of GUI.
Generally speaking, AWT GUI is inaccessible because it does not provide APIs for
AWT programmers to specify accessible information.
Because of variations between operating systems, a component might look, or
even act, differently on different platforms. This variability threatened java’s
philosophy: write once, run anywhere.
The look and feel of each component was fixed and could not be changed.
The use of heavyweight components caused some frustrating restrictions. Due to
these limitations Swing came and was integrated to java.
AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
AWT provides less components than Swing provides more powerful
Swing. Components such as tables, lists, scroll
panes, color chooser, tabbed pane etc
AWT doesn't follows MVC Swing follows MVC.
// AWT Example
importjava.awt.*;
public class AwtDemo
{
AwtDemo()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
//adding a new Button.
f.add(btn);
//setting size.
f.setSize(300, 250);
//setting title.
f.setTitle("Java Programming");
f.setLayout(null);
//set frame visibility true.
f.setVisible(true);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
//creating a frame.
AwtDemo awt = new AwtDemo();
}
}
OUTPUT:
D:\TKREC\Java>javac AwtDemo.java
D:\TKREC\Java>java AwtDemo
import java.awt.*;
public class AwtApplication extends Frame
{
AwtApplication()
{
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
AwtApplication awt = new AwtApplication();
}
}
OUTPUT:
D:\Java>javac AwtApplication.java
D:\Java>java AwtApplication
MVC architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
Swing component has Model as a separate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.
Now we can use JApplet that can have all the controls of swing. The JApplet class
extends the Applet class
import javax.swing.*;
P.Ramesh, Assistant Professor, AIMLDept, TKREC 14
OOP through Java UNIT-5
import java.awt.*;
import java.awt.event.*;
/*
<applet code="SwingApplet" width=220 height=110>
</applet>
*/
public class SwingApplet extends JApplet
{
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
OUTPUT:
D:\TKREC\Java> javac SwingApplet.java
D:\TKREC\Java> appletviewer SwingApplet.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/* This class extends JPanel. It overrides the paintComponent() method so that random
lines are plotted in the panel.*/
Insets ins;
// used to generate random numbers
Random rand;
// Construct a panel.
PaintPanel()
{
// Put a border around the panel.
setBorder(BorderFactory.createLineBorder(Color.blue, 5));
rand = new Random();
}
// Override the paintComponent() method.
protected void paintComponent(Graphics g)
{
// Always call the superclass method first.
super.paintComponent(g);
int x, y, x2, y2;
// Get the height and width of the component.
int height = getHeight();
int width = getWidth();
jfrm.add(pp);
jfrm.setVisible(true);
}
public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new PaintDemo();
}
});
}
}
OUTPUT:
D:\Java>javac PaintDemo.java
D:\TKREC\Java> java PaintDemo
The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=200>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Create an icon.
ImageIcon ii = new ImageIcon(“Hourglass.gif");
// Create a label.
JLabel jl = new JLabel("Hourglass", ii, JLabel.CENTER);
OUTPUT:
D:\Java>javac JLabelDemo.java
D:\Java> appletviewer JLabelDemo.java
JText Field
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
// Demonstrate JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=100>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
}
}
OUTPUT:
D:\TKREC\Java>javac JTextFieldDemo.java
D:\TKREC\Java> appletviewer JTextFieldDemo.java
Here, str and icon are the string and icon used for the button.
When the button is pressed, an ActionEvent is generated. Using the ActionEvent object
passed to the actionPerformed( ) method of the registered ActionListener, you can
obtain the action command string associated with the button.You can obtain the action
command by calling getActionCommand( ) on the event object. It is declared like this:
String getActionCommand( )
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=200 height=300>
</applet>
*/
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Change to flow layout.
setLayout(new FlowLayout());
OUTPUT:
D:\Java>javac JButtonDemo.java
D:\Java>appletviewer JButtonDemo.java
JCheck Boxes
The JCheckBox class provides the functionality of a check box. Its immediate superclass
is JToggleButton, which provides support for two-state buttons, as just described.
The JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed
to the itemStateChanged( ) method defined by ItemListener. The easiest way to
determine the selected state of a check box is to call isSelected( ) on the JCheckBox
instance.
// Demonstrate JCheckbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=250 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet implements ItemListener
{
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Change to flow layout.
setLayout(new FlowLayout());
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
OUTPUT:
D:\TKREC\Java>javac JCheckBoxDemo.java
D:\TKREC\Java appletviewer JCheckBoxDemo.java
JRadio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time. They are supported by the JRadioButton class, which
extends JToggleButton.
JRadioButton provides several constructors. The one used in the example is shown
here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.
A button group is created by the ButtonGroup class. Its default constructor is invoked
for this purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
A JRadioButton generates action events, item events, and change events each time the
button selection changes. Most often, it is the action event that is handled, which means
that you will normally implement the ActionListener interface.
// Demonstrate JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=280 height=50>
</applet>
*/
OUTPUT:
D:\TKREC\Java>javac JRadioButtonDemo.java
D:\TKREC\Java>appletviewer JRadioButtonDemo.java
JCombo Box
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it will also
display a dropdown list that allows a user to select a different entry. You can also create
a combo box that lets the user enter a selection into the text field.
The JComboBox constructor used by the example is shown here:
JComboBox(E[ ] items) Here, items is an array that initializes the combo box. Other
constructors are available
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries can
be changed) use the MutableComboBoxModel.
JComboBox generates an action event when the user selects an item from the list.
JComboBox also generates an item event when the state of selection changes, which
occurs when an item is selected or deselected.
One way to obtain the item selected in the list is to call getSelectedItem( ) on the combo
box. It is shown here:
Object getSelectedItem()
// Demonstrate JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=250>
</applet>
*/
// Handle selections.
jcb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".png"));
}
});
add(jlab);
}
}
OUTPUT:
D:\TKREC\Java>javac JComboBoxDemo.java
D:\TKREC\Java> appletviewer JComboBoxDemo.java
JTabbed Pane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking
them with tabs. Selecting a tab causes the component associated with that tab to come
to the forefront. Tabbed panes are very common in the modern GUI.
JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=300 height=250>
</applet>
*/
{
CitiesPanel()
{
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
OUTPUT:
D:\TKREC\Java>javac JTabbedPaneDemo.java
D:\TKREC\Java>appletviewer JTabbedPaneDemo.java
JScroll Pane
JScroll Pane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can be either an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel.
The viewable area of a scroll pane is called the viewport. It is a window in which the
component being scrolled is displayed. JScrollPane defines several constructors. The
one used in this chapter is shown here:
JScrollPane(Component comp)
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
/* Add the scroll pane to the content pane.Because the default border layout is used,
the scroll pane will be added to the center
*/
add(jsp, BorderLayout.CENTER);
}
}
OUTPUT:
D:\TKREC\Java>javac JScrollPaneDemo.java
D:\TKREC\Java> appletviewer JScrollPaneDemo.java
Trees
A tree is a component that presents a hierarchical view of data. The user has the ability
to expand or collapse individual subtrees in this display. Trees are implemented in
Swing by the JTree class.
// Demonstrate JTree.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=300 height=250>
</applet>
*/
JTable
JTable is a component that displays rows and columns of data. JTable does not provide
any scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a
JScrollPane.
Here are the steps required to set up a simple JTable that can be used to display
data:
Create an instance of JTable.
Create a JScrollPane object, specifying the table as the object to scroll.
Add the table to the scroll pane.
Add the scroll pane to the content pane.
// Demonstrate JTable.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
}
}
OUTPUT:
D:\Java>javac JTableDemo.java
D:\Java>appletviewer JTableDemo.java