Java - 5
Java - 5
5.1 APPLETS
Applets do not use the main() method for initiating the execution
of the code. Applets when loaded automatically call certain methods
of Applet class to start and execute the applet code. Applets cannot
run any program from the local computer and they are restricted from
using libraries from other languages such as C or C++.
import java.awt.*;
import java.applet.*;
public class appletclassname extends Applet
{
public void paint(Graphics g)
{
//Applet operations code
}
}
M.BALASUBRAMANIAN /AP/HOD OF CS
5.2 Java Programming
Example
Applets001.java
import javax.swing.JApplet;
import java.awt.*;
public class Applets001 extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.black);
g.fillOval(60, 40, 220, 220);
g.setColor(Color.red);
g.fillOval(80, 60, 180, 180);
}
}
Applets001.html
<HTML>
<HEAD>
<TITLE>This is my first Applet</TITLE>
</HEAD>
<BODY>
<APPLET code="Applets001.class" codebase="."
width=400 height=300></APPLET>
</BODY>
</HTML>
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.3
5.1.2 Applet class
Methods Description
void init() The first method to be called when
an applet begins its execution.
void start() Called automatically after init()
method to start the execution of
an applet.
void stop() Called when an applet has to
pause/stop its execution.
void destoy() Called when an appLet us finally
terminated.
String getParameter(String Returns the value of a parameter
ParameterName) defined in an applet
M.BALASUBRAMANIAN /AP/HOD OF CS
5.4 Java Programming
OO Get the network location of the HTML file that contains the
applet
OO Fetch an image
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.5
OO Destroy the applet
init( )
Born
state
Start( ) Stop( )
Run
state Idle
state
Start( ) Destory( )
Dead
state
There are five methods of an applet life cycle, and they are:
1. init()
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.7
2. start()
3. paint()
4. stop()
5. destroy()
M.BALASUBRAMANIAN /AP/HOD OF CS
5.8 Java Programming
5.1.4 Steps for developing an applet program
5. Run the applet: To run the applet we have two ways. They are
using HTML program and using applet viewer tool.
Syntax
<applet code =”.class file of the applet” height = height value width
= widthvalue>
</applet>
Example
File name: MyApp.html
<HTML>
<HEAD>
<TITLE> My applet example </TITLE>
</HEAD>
<BODY>
<APPLET code="MyApp" height=100 width=150> </APPLET>
</BODY>
</HTML>
Using appletviewer
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.9
Syntax
appletviewer filename.java
Example
appletviewer MyApp.java
Example
import java.applet.*;
import java.awt.*;
/*<applet code="MyApp1" height=300 width=300> </ap-
plet>*/
public class MyApp1 extends Applet
{
String s=" ";
public void init ()
{
M.BALASUBRAMANIAN /AP/HOD OF CS
5.10 Java Programming
setBackground (Color.green);
setForeground (Color.red);
s=s+" INIT ";
}
public void start ()
{
s=s+" START ";
}
public void stop ()
{
s=s+" STOP ";
}
public void destroy ()
{
s=s+" DESTROY ";
}
public void paint (Graphics g)
{
Font f=new Font ("arial", Font.
BOLD, 40);
g.setFont (f);
g.drawString (s,100,100);
}
};
5.1.5 Passing values through parameters
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.11
Signature of the getParamter() method
Example
import java.awt.*;
import java.applet.*;
/* <applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/
public class Applet8 extends Applet
{
String name;
String age;
String sport;
String food;
String fruit;
String destination;
M.BALASUBRAMANIAN /AP/HOD OF CS
5.12 Java Programming
public void init()
{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}
public void paint(Graphics g)
{
g.drawString("Reading parameters passed to
this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit, 20,
80);
g.drawString("Favorite food -" + food, 20,
100);
g.drawString("Favorite destination -" + name,
20, 120);
g.drawString("Favorite sport -" + sport, 20,
140);
}
Output
appletviewer Applet8.java
Where Applet8.java is the name of java file that contains the code
of an applet. Right after running the applet program using appletviewer
a new applet window is displayed to us -
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.13
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.15
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300"
height="300"> </applet>
</body>
</html>
5.1.7 Event-handling
M.BALASUBRAMANIAN /AP/HOD OF CS
5.16 Java Programming
OO ItemListener interface and have implemented its
itemStateChanged() method to listen to checking/unchecking
of checkboxes or radio boxes in our program.
Applet2.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Applet2" width=250 height=200> </ap-
plet> */
public class Applet2 extends Applet implements Ac-
tionListener, ItemListener
{
Label label1, label2, label3;
TextField tf1, tf2, tf3;
Checkbox ck1, ck2;
CheckboxGroup cb;
public void init()
{
System.out.println("Initializing an applet");
label1 = new Label("Enter your name");
tf1= new TextField(10);
label2 = new Label("Enter your city");
tf2= new TextField(10);
label3 = new Label("Gender");
cb= new CheckboxGroup();
ck1 = new Checkbox("Male",cb,false);
ck2 = new Checkbox("Female",cb,false);
add(label1);
add(tf1);
add(label2);
add(tf2);
add(label3);
add(ck1);
add(ck2);
tf1.addActionListener(this);
tf2.addActionListener(this);
ck1.addItemListener(this);
ck2.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.17
{
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Your name is "+ tf1.get
Text(), 10, 150 );
g.drawString("Your city is "+ tf2.get
Text(), 10,170 );
if(cb.getSelectedCheckbox()!=null)
{
g.drawString("Your gender is "+ cb.get
SelectedCheckbox().getLabel(), 10,190);
}
}
}
Output
appletviewer Applet2.java
M.BALASUBRAMANIAN /AP/HOD OF CS
5.18 Java Programming
5.2 GUI APPLICATIONS - PART 1
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.19
OO Properties window. Displays the editable settings for the
currently selected component.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.20 Java Programming
Creating and Showing Frames
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.21
OO You can also specify that the frame have no window decorations
at all, a feature that can be used on its own, or to provide your
own decorations, or with full-screen exclusive mode.
OO The third frame uses Java look and feel window decorations,
but has a custom icon.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.22 Java Programming
decorations provided by the window system Custom icon;
window decorations provided by the look and feel
Declaration
Constructor Description
JOptionPane() It is used to create a JOptionPane
with a test message.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.23
JOptionPane(Object message) It is used to create an instance
of JOptionPane to display a
message.
JOptionPane(Object message, int It is used to create an instance
messageType of JOptionPane to display a
message with specified message
type and default options.
Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void It is used to create an information-
showMessageDialog(Component message dialog titled "Message".
parentComponent, Object
message)
static void It is used to create a message
showMessageDialog(Component dialog with given title and
parentComponent, Object message, messageType.
String title, int messageType)
static int It is used to create a dialog with
showConfirmDialog(Component the options Yes, No and Cancel;
parentComponent, Object with the title, Select an Option.
message)
static String It is used to show a question-
showInputDialog(Component message dialog requesting
parentComponent, Object input from the user parented to
message) parentComponent.
void setInputValue(Object It is used to set the input value
newValue) that was selected or input by the
user.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.24 Java Programming
Java JOptionPane Example: showMessageDialog()
import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello,
Welcome to Javatpoint.");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.25
Successfully Updated.","Alert",
JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args)
{
new OptionPaneExample();
}
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
5.26 Java Programming
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.27
{
new OptionPaneExample();
}
}
Output
OO Free Design enables you to lay out your form using visual
guidelines that automatically suggest optimal alignment
and spacing of components. As you work, the GUI Builder
translates your design decisions into a functional UI without
requiring you to specify a layout manager.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.28 Java Programming
whenever you resize the form or switch locales the GUI
adjusts to accommodate your changes without changing the
relationships between components.
FlowLayout
BorderLayout
GridLayout
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.29
GridBagLayout
CardLayout
BoxLayout
AbsoluteLayout
M.BALASUBRAMANIAN /AP/HOD OF CS
5.30 Java Programming
you want them in the form, move them around in the IDE, and resize
them using their selection borders. It is particularly useful for making
prototypes since there are no formal limitations and you do not have
to enter any property settings. However, it is not recommended
for production applications since the fixed locations and sizes of
components do not change with the environment.
Null Layout
1. Right-click the node for the container whose layout you wish to
change.
2. In the contextual menu, choose the desired layout from the Set
Layout submenu.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.31
5.2.5 AWT component classes
OO AWT is heavy weight i.e. its components are using the resources
of underlying operating system (OS).
Syntax
import java.awt.*;
<className>()
M.BALASUBRAMANIAN /AP/HOD OF CS
5.32 Java Programming
setVisible(true);//set visibility of container to true
OO TextField
OO Label
OO TextArea
OO RadioButton, CheckBox
OO Choice
OO List
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.33
components and AWT directly calls the native subroutine that creates
those components. In simple words, an AWT application will look like
a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.
Components
All the elements like the button, text fields, scroll bars, etc. are
called components. In Java AWT, there are classes for each component
M.BALASUBRAMANIAN /AP/HOD OF CS
5.34 Java Programming
as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
Container
Types of containers
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window.
We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or
menu bar. It is generic container for holding the components. It can
have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.35
have menu bars. It can have other components like button, text field,
scrollbar etc. Frame is most widely used container while developing an
AWT application.
Method Description
public void add(Component c) Inserts a component on this
component.
public void setSize(int width,int Sets the size (width and height)
height) of the component.
public void Defines the layout manager for
setLayout(LayoutManager m) the component.
public void setVisible(boolean Changes the visibility of the
status) component, by default false.
AWTExample1.java
import java.awt.*;
public class AWTExample1 extends Frame
{
AWTExample1()
{
Button b = new Button("Click Me!!");
M.BALASUBRAMANIAN /AP/HOD OF CS
5.36 Java Programming
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
AWTExample1 f = new AWTExample1();
}
}
Output:
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.37
AWTExample2.java
import java.awt.*;
class AWTExample2
{
AWTExample2()
{
Frame f = new Frame();
Label l = new Label("Employee id:");
Button b = new Button("Submit");
TextField t = new TextField();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b);
f.add(l);
f.add(t);
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
AWTExample2 awt_obj = new AWTExample2();
}
}
Output:
M.BALASUBRAMANIAN /AP/HOD OF CS
5.38 Java Programming
The class Component is the abstract base class for the non
menu user-interface controls of AWT. Component represents an
object with graphical representation. Java Swing tutorial is a part of
Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java. Java Swing provides platform-
independent and lightweight components. The javax.swing package
provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Field
Class Constructors
Class Methods
M.BALASUBRAMANIAN /AP/HOD OF CS
5.40 Java Programming
Method Description
public void add(Component c) add a component on another
component.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.41
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the
component. It is by default false.
For example
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating in
stance of JFrame
JButton b=new JButton("click");//creat
ing instance of JButton
b.setBounds(130,100,100, 40);//x axis,
y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500
height
f.setLayout(null);//using no layout man
agers
f.setVisible(true);//making the frame
visible
}
}
M.BALASUBRAMANIAN /AP/HOD OF CS
5.42 Java Programming
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.43
Simple example of Swing by inheritance
import javax.swing.*;
public class Simple2 extends JFrame
{
JFrame f;
Simple2()
{
JButton b=new JButton("click");//create
button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new Simple2();
}
}
5.3 GUI APPLICATIONS PART 2:
M.BALASUBRAMANIAN /AP/HOD OF CS
5.44 Java Programming
To define an event handler using the property sheet:
3. Add your code for the new event handler in the Source Editor.
3. Select the event in the property sheet and click the ellipsis (...)
button to display the Handlers dialog box. Click the Add button
and fill out the form. Repeat these steps to add additional event
handlers.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.45
To remove event handlers:
3. Select the event in the property sheet and click the ellipsis (...)
button to display the Handlers dialog box. Select the unwanted
handler and click the Remove button. Alternately, go to the
Properties window and delete the name of the handler you want
to remove.
List: This component can hold a list of text items. This component
allows a user to choose one or more options from all available options
in the list.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.47
Checkbox: This component is used to create a checkbox of GUI
whose state can be either checked or unchecked.
The Graphics class is the abstract super class for all graphics
contexts which allow an application to draw onto components that can
be realized on various devices, or onto off-screen images as well. A
Graphics object encapsulates all state information required for the basic
rendering operations that Java supports. State information includes the
following properties.
Class constructors
Graphics() ()
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.49
Class methods
abstract void copyArea(int x, int y, int width, int height, int dx, int
dy)
Creates a new Graphics object based on this Graphics object, but with
a new translation and clip area.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.50 Java Programming
void drawBytes(byte[] data, int offset, int length, int x, int y)
Draws the text given by the specified byte array, using this graphics
context's current font and color.
Draws the text given by the specified character array, using this graphics
context's current font and color.
Draws as much of the specified image as has already been scaled to fit
inside the specified rectangle.
Draws as much of the specified image as has already been scaled to fit
inside the specified rectangle.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int
dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver
observer)
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.51
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2,
int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and
(x2, y2) in this graphics context's coordinate system.
void drawPolygon(Polygon p)
M.BALASUBRAMANIAN /AP/HOD OF CS
5.52 Java Programming
Renders the text of the specified iterator applying its attributes in
accordance with the specification of the TextAttribute class.
Draws the text given by the specified string, using this graphics
context's current font and color.
abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Fills an oval bounded by the specified rectangle with the current color.
void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the
graphics context's current color.
Fills the specified rounded corner rectangle with the current color.
void finalize()
Rectangle getClipBounds(Rectangle r)
Rectangle getClipRect()
FontMetrics getFontMetrics()
Returns true if the specified rectangular area might intersect the current
clipping area.
Sets the current clip to the rectangle specified by the given coordinates.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.54 Java Programming
Sets the current clipping area to an arbitrary clip shape.
abstract void setColor(Color c)
Sets this graphics context's current color to the specified color.
abstract void setFont(Font font)
Sets this graphics context's font to the specified font.
abstract void setPaintMode()
Sets the paint mode of this graphics context to overwrite the destination
with this graphics context's current color.
abstract void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this
graphics context's current color and the new specified color.
String toString()
Translates the origin of the graphics context to the point (x, y) in the
current coordinate system.
Example program
package com.example.demo;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTGraphicsDemo extends Frame
{
public AWTGraphicsDemo()
{
super("Java AWT Examples");
prepareGUI();
}
public static void main(String[] args)
{
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.55
AWTGraphicsDemo awtGraphicsDemo = new AWT-
GraphicsDemo();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI()
{
setSize(400,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent win-
dowEvent)
{
System.exit(0);
}
});
}
@Override
public void paint(Graphics g)
{
g.setColor(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to learn Java", 50, 150);
}
}
Output
M.BALASUBRAMANIAN /AP/HOD OF CS
5.56 Java Programming
5.3.4 Other Swing Controls.
OO JLabel
OO JRadioButton
OO ButtonGroup
OO JCheckBox
OO JTextField
OO JTextArea
OO JButton
OO Border
OO JComboBox
OO JTabbedPane
OO JPasswordField
JLabel
JLabel Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
5.58 Java Programming
new JLabelDemo ();
}
}
Output
JRadioButton
This component allows the user to select only one item from a
group item. By using the JRadioButton component you can choose one
option from multiple options.
JRadioButton Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.59
OO JRadioButton(Label, boolean): It is used to create a radio
button with the specified text and selected status.
ButtonGroup
Example : add(jrb);
JCheckBox
JCheckBox Constructors
JTextField
M.BALASUBRAMANIAN /AP/HOD OF CS
5.60 Java Programming
Declaration: public class JTextField extends JTextComponent
implements SwingConstants
JTextField Constructors
JTextArea
JTextArea Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.61
OO JTextarea(String s, int row, int column): It is used to create
a text area with the specified number of rows and columns that
display specified text.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.62 Java Programming
bcd.addActionListener (this);
ccb.addActionListener (this);
acb.addActionListener (this);
c.add (eng);
c.add (doc);
c.add (jtf);
c.add (bcd);
c.add (ccb);
c.add (acb);
c.add (jta);
this.setVisible (true);
this.setSize (500, 500);
this.setTitle ("Selection Example");
this.setDefaultCloseOperation (JFrame.
EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == eng)
{
jtf.setText ("You are an Engineer");
}
if (ae.getSource () == doc)
{
jtf.setText ("You are an Doctor");
}
String str = " ";
if (bcd.isSelected ())
{
str += "Bike\n";
}
if (ccb.isSelected ())
{
str += "Car\n";
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.63
}
if (acb.isSelected ())
{
str += "Aeroplane\n";
}
jta.setText (str);
}
public static void main (String[]args)
{
new SwingDemo2 ();
}
}
Output
JButton
JButton Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
5.64 Java Programming
OO JButton(String s): It is used to create a button with the
specified text.
Border
Component.setBorder(Border);
Methods of Border
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.65
uses it. Here, the color argument specifies the color which with
the border should fill its area. Here, the icon argument specifies
the icon which with the border should tile its area.
OO CompoundBorder createCompoundBorder(Border,
Border): Combine two borders into one. Here, the first
argument specifies the outer border; the second, the inner
border.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.66 Java Programming
{
button[count] = new JButton ("Button
" + (count + 1));
panel.add (button[count]);
}
button[0].setBorder (BorderFactory.cre-
ateLineBorder (Color.
blue));
button[1].setBorder (BorderFactory.createBev-
elBorder (0));
button[2].setBorder (BorderFactory.createBev-
elBorder (1, Color.
red, Color.blue));
button[3].setBorder (BorderFactory.createBev-
elBorder (1, Color.
green, Color.orange,Color.red, Color.blue));
button[4].setBorder (BorderFactory.createEmp-
tyBorder (10, 10,
10, 10));
button[5].setBorder (BorderFactory.cre-
ateEtchedBorder (0));
button[6].setBorder (BorderFactory.createTi-
tledBorder ("Titled
Border"));
add (panel, BorderLayout.CENTER);
setSize (400, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_
CLOSE);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[]args)
{
new JButtonDemo ();
}
}
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.67
Output
JComboBox
Example: jcb.addItem(item);
JComboBox Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
5.68 Java Programming
OO JComboBox(Vector<?> items): It is used to create a
JComboBox that contains the elements in the specified Vector.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.69
JTabbedPane
It is a pane that can contain tabs and each tab can display any
component in the same pane. It is used to switch between a group of
components by clicking on a tab with a given title or icon. To add the
tabs to the JTabbedPane we can use the following methods:
OO jtp.add(TabName, Components)
OO jtp.addTab(TabName, Components)
JTabbedPane Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
5.70 Java Programming
OO JTabbedPane(int tabPlacement, int tabLayoutPolicy): It
is used to create an empty TabbedPane with a specified tab
placement and tab layout policy.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.71
Output
JPasswordField
JPasswordFiled Constructors
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.73
QUESTIONS AND ANSWERS
PART-A (2 MARKS)
1. What is an Applet?
An applet is a small Java program that is embedded and ran in
some other Java interpreter program such as
OO a Java technology-enabled browser
OO Sun’s applet viewer program called appletviewer
Applets do not use the main() method for initiating the execution of
the code.
2. Define types of Applet.
OO Applets based on the AWT(Abstract Window Toolkit) package
by extending its Applet class.
OO Applets based on the Swing package by extending its JApplet
class
3. What are all the methods of Applet Class?
OO void init()-The first method to be called when an applet begins
its execution.
OO void start()- Called automatically after init() method to start the
execution of an applet.
OO void paint(): The paint() method belongs to the Graphics class
in Java. It is used to draw shapes like circle, square, trapezium,
etc., in the applet.
4. Write syntax for entire Applet Lifecycle.
class TestAppletLifeCycle extends Applet
{
public void init()
{
M.BALASUBRAMANIAN /AP/HOD OF CS
5.74 Java Programming
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{
// draw the shapes
}
public void stop()
{
// code to stop the applet
}
public void destroy()
{
// code to destroy the applet
}
}
5. How to pass the parameters in Applet?
OO To pass the parameters to the Applet we need to use the param
attribute of <applet> tag.
OO To retrieve a parameter's value, we need to use the getParameter()
method of Applet class.
void stop() Called when an applet has to pause/stop its
execution.
void destoy() Called when an appLet us finally terminated.
6. Write any two Graphics class in Java.
java.awt.Graphics class provides many methods for graphics
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.75
programming. Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used
to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
7. What is Event Handling?
An event in a java program is generated upon clicking a button,
typing in a textfield, checking a checkbox or radio box, selecting an
item in a drop down list etc
To listen events, we must implement interfaces related to the
kind of event that is generated by our program. For example, if our
program has a button in it and in order to listen a button click event, we
must implement ActionListener interface and implement its method
actionPerformed(), which gives us the name of the button that was
clicked, that lead to a button click event.
8. What is a GUI?
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.
9. How to create Dialogue boxes in GUI applications?
The JOptionPane class is used to provide standard dialog boxes
such as message dialog box, confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.
10. Write any three` layout managers in GUI application.
FlowLayout
BorderLayout
GridLayout
M.BALASUBRAMANIAN /AP/HOD OF CS
5.76 Java Programming
REVIEW QUESTIONS
PART - B (5 MARKS)
1. Give a detailed information about Applet Class.
M.BALASUBRAMANIAN /AP/HOD OF CS