Unit 2
Unit 2
AppletContext
getAppletContext( ) Returns the context associated with the applet
AudioClip
getAudioClip(URL
Returns an AudioClip object that encapsulates the
url
audio clip found at the location specified by url
)
audioClip AudioClip object that encapsulates the audio clip
getAudioClip(URL found at the location specified by url and having the
name specified by clipName.
url , String clipName )
void play(URL
url
If an audio clip is found at the location specified by
, String
url with the name specified by clipName,
clipName
the clip is played
)
void resize(int
width
, int Resizes the applet according to the dimensions
height specified by width and height
)
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
Lifecycle methods for Applet:
By html file.
By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After
that create an html file and place the applet code in html file. Now click the
html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
} }
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
} }
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
*/
public class Applet11 extends Applet
{
String statusBar;
public void init()
{
statusBar= getParameter("StatusBar");
}
public void paint(Graphics g)
{
g.drawString("Reading the applet parameter to set status bar message - ",
20, 20);
//Setting a message at the status bar of our applet.
showStatus(statusBar);
g.drawString("Setting the status bar message -" + statusBar, 20, 100);
}
}
In order to run our applet using appletviewer, type the following command
at the command prompt-
appletviewer Applet11.java
Where Applet11.java is the name of java file that contains the code of
an applet. We have passed a parameter to an applet, named
StatusBar with the value Have a good day.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
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);
} }
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Container classes are classes that can have other components on it. So
for creating a Java Swing GUI, we need at least one container object. There
are 3 types of Java Swing containers.
Panel: It is a pure container and is not a window in itself. The sole
purpose of a Panel is to organize the components on to a window.
Frame: It is a fully functioning window with its title and icons.
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 in Java
Now in this Java GUI Tutorial, let’s understand how to create a GUI in Java
with Swings in Java examples.
Example:How to make a GUI in Java.
Step 1) Copy the following code into an editor
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 button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of
frame
frame.setVisible(true);
}
}
Step 2) Save, Compile, and Run the code.
Step 3) Now let’s Add a Button to our frame. Copy following code into an
editor from given Java UI Example
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);
}
}
Step 4) Execute the code. You will get a big button
Step 5) How about adding two buttons? Copy the following code into an
editor.
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("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}}
Step 6) Save , Compile , and Run the program.
Step 7) Unexpected output =? Buttons are getting overlapped.
Step 8) How about creating a chat frame like below?
Try to code yourself before looking at the program below.
//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String args[]) {
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//Creating the MenuBar and adding components
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);
//Creating the panel at bottom and adding components
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
// Text Area at the Center
JTextArea ta = new JTextArea();
//Adding Components to the frame.
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}}
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout:The BorderLayout is used to arrange the components in five
regions: north, south, east, west, and center. Each region (area) may contain one component only.
It is the default layout of a frame or window. The BorderLayout provides five constants for each
region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between
the components.
BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
Checkboxes (java.awt.Checkbox)
Checkboxes ave two states, on and off. The state of the button is
returned as the Object argument, when a Checkbox event occurs. To find
out the state of a checkbox object we can use getState() that returns a true
or false value. We can also get the label of the checkbox using getLabel()
that returns a String object.
Radio Buttons (java.awt.CheckboxGroup)
Is a group of checkboxes, where only one of the items in the group can
be selected at any one time.
Choice Buttons (java.awt.Choice)
Are areas where the user can enter text. They are useful for displaying
and receiving text messages. We can make this textfield read-only or
editable. We can use the setEditable(false) to set a textfield read-only.
There are numerous ways that we can construct a Textfield object:
TextField text1 = new TextField(); // no properties
TextField text2 = new TextField("Some text"); // a textfield with a
// predefined String
TextField text3 = new TextField(40); // a textfield with a
// predefined size
TextField text4 = new TextField("Some text", 50); // combination of the two
An Example Component Application
To show these components in action we can write a short piece of code that
displays these components, but they do not have any events behind them -
they work visually but do not have any true program function. “A
Component Applet” shows an example applet that details all the previous
components.
You can see this applet running here - ComponentApplet.html and the code
segment is here - ComponentApplet.java
// The Component Applet that displays several components
import java.applet.Applet;
import java.awt.*;
public class ComponentApplet extends Applet
{ public void init()
{ Button b = new Button("Test Button");
this.add(b);
Checkbox cb = new Checkbox("Test Checkbox");
this.add(cb);
CheckboxGroup cbg = new CheckboxGroup();
this.add(new Checkbox("CB Item 1", cbg, false));
this.add(new Checkbox("CB Item 2", cbg, false));
this.add(new Checkbox("CB Item 3", cbg, true));
Choice choice = new Choice();
choice.addItem("Choice Item 1");
choice.addItem("Choice Item 2");
choice.addItem("Choice Item 3");
this.add(choice);
Label l = new Label("Test Label");
this.add(l);
TextField t = new TextField("Test TextField",30);
this.add(t);
}}
AWT SWING
Platform Dependent Platform Independent
Does not follow MVC Follows MVC
Lesser Components More powerful components
Does not support pluggable look and Supports pluggable look and feel
feel
Heavyweight Lightweight
All the components in swing like JButton, JComboBox, JList, JLabel are
inherited from the JComponent class which can be added to the container
classes. Containers are the windows like frame and dialog boxes. Basic swing
components are the building blocks of any gui application. Methods like
setLayout override the default layout in each container. Containers like
JFrame and JDialog can only add a component to itself. Following are a few
components with examples to understand how we can use them.
JButton Class
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}Output:
JTextField Class
JScrollBar Class
JPanel Class
JMenu Class
Output:
JList Class
It inherits JComponent class, the object of JList class represents a list of
text items.
import javax.swing.*;
public class Example
{
Example( ){
JLabel Class
JComboBox Class
2.13 BORDERS
Any Swing component can have a decorative border. JComponent
includes a method called setBorder() ; all you have to do is call it, passing it
an appropriate implementation of the Border interface. Swing provides many
useful Border implementations in the javax.swing.border package. You could
create an instance of one of these classes and pass it to a component’s
setBorder() method, but there’s an even simpler technique.
The BorderFactory class creates any kind of border for you using static
“factory” methods. Creating and setting a component’s border, then, is
simple:
JLabel labelTwo = new JLabel("I have an etched border.");
labelTwo.setBorder(BorderFactory.createEtchedBorder());
BorderFactory is convenient, but it does not offer every option of every
border type. For example, if you want to create a raised EtchedBorder
instead of the default lowered border, you’ll need to use EtchedBorder’s
constructor, like this:
JLabel labelTwo = new JLabel("I have a raised etched border.");
labelTwo.setBorder( new EtchedBorder(EtchedBorder.RAISED) );
The Border implementation classes are listed and briefly described here:
BevelBorder:This border draws raised or lowered beveled edges, giving an
illusion of depth.
SoftBevelBorder:This border is similar to BevelBorder, but thinner.
EmptyBorder:Doesn’t do any drawing, but does take up space. You can use
it to give a component a little breathing room in a crowded user interface.
EtchedBorder:A lowered etched border gives the appearance of a rectangle
that has been chiseled into a piece of stone. A raised etched border looks
like it is standing out from the surface of the screen.
LineBorder:Draws a simple rectangle around a component. You can specify
the color and width of the line in LineBorder’s constructor.
MatteBorder:A souped-up version of LineBorder. You can create a
MatteBorder with a certain color and specify the size of the border on the
left, top, right, and bottom of the component. MatteBorder also allows you to
pass in an Icon that will be used to draw the border. This could be an image
(ImageIcon) or any other implementation of the Icon interface.
TitledBorder:A regular border with a title. TitledBorder doesn’t actually
draw a border; it just draws a title in conjunction with another border object.
You can specify the locations of the title, its justification, and its font. This
border type is particularly useful for grouping different sets of controls in a
complicated interface.
CompoundBorder:A border that contains two other borders. This is
especially handy if you want to enclose a component in an EmptyBorder and
then put something decorative around it, such as an EtchedBorder or a
MatteBorder.
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button:public void addActionListener(ActionListener a){ }
MenuItem
We can put the event handling code into one of the following places:
Within class
Other class
Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
} }
public void setBounds(int xaxis, int yaxis, int width, int
height); have been used in the above example that sets the position of
the component it may be button, textfield etc.
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
} }
2.15 FILECHOOSER
The object of JFileChooser class represents a dialog window from which
the user can select file. It inherits JComponent class and .JFileChooser class
declaration
Let's see the declaration for javax.swing.JFileChooser class.
public class JFileChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
Constructs a JFileChooser pointing to the
JFileChooser()
user's default directory.
JFileChooser(File Constructs a JFileChooser using the given
currentDirectory) File as the path.
JFileChooser(String Constructs a JFileChooser using the given
currentDirectoryPath) path.
Example:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
} } }
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
} }
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] Creates a JTree with every element of the specified array
value) as the child of a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root,
root) which displays the root node.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
2.18 TABLE
The JTable class is used to display data in tabular form. It is composed
of rows and columns.
JTable class declaration
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified
columns) data.
Java JTable Example
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:
2.19 TABBEDPANELS
The JTabbedPanel class is used to switch between a group of
components by clicking on a tab with a given title or icon. It inherits
JComponent class.
JTabbedPanel class declaration
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a
default tab placement of JTabbedPane.Top.
JTabbedPane(int Creates an empty TabbedPane with a
tabPlacement) specified tab placement.
JTabbedPane(int Creates an empty TabbedPane with a
tabPlacement, int specified tab placement and tab layout
tabLayoutPolicy) policy.
Java JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
Output:
2.20 PROGRESSIVE BAR
The JProgressBar class is used to display the progress of the task. It inherits JComponent
class.
JProgressBar class declaration
Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string text.
JProgressBar(int min, int It is used to create a horizontal progress bar with the specified
max) minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar with the specified orientation, it
can be either Vertical or Horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, It is used to create a progress bar with the specified orientation,
int min, int max) minimum and maximum value.
Constructor Description
JSlider() creates a slider with the initial value of 50 and
range of 0 to 100.
JSlider(int orientation) creates a slider with the specified orientation
set by either JSlider.HORIZONTAL or
JSlider.VERTICAL with the range 0 to 100 and
initial value 50.
JSlider(int min, int max) creates a horizontal slider using the given min
and max.
JSlider(int min, int max, creates a horizontal slider using the given min,
int value) max and value.
JSlider(int orientation, int creates a slider using the given orientation, min,
min, int max, int value) max and value.
Commonly used Methods of JSlider class
Method Description
public void It is used to set the minor tick
setMinorTickSpacing(int n) spacing to the slider.
public void It is used to set the major tick
setMajorTickSpacing(int n) spacing to the slider.
public void setPaintTicks(boolean It is used to determine whether tick
b) marks are painted.
public void setPaintLabels(boolean It is used to determine whether
b) labels are painted.
public void setPaintTracks(boolean It is used to determine whether track
b) is painted.
Java JSlider Example
import javax.swing.*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel); }
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
frame.pack();
frame.setVisible(true); } }
Output: