Java Applets using Swing
Document Sample


Java Applets using Swing
Brian C. Hoffman
IMMT and E-Business Conference
June 26th, 2003
Goals and Objectives
To understand the following terminology
Java
Object Oriented Programming
Swing
Java Applet
To understand inheritance and the life cycle of a Java Applet
To be able to write a simple Applet
To understand how to insert Swing GUI components such as
text boxes and buttons into an Applet
To understand layout managers and panels
To be able to handle events generated by GUI components
What is Java?
Java is an object oriented language developed by James Gosling
and coworkers at SUN Microsystems.
Java began as a hardware independent language for powering
small hand-held devices such as complex remotes.
Java’s hardware independence made it ideal for use on the web
and in 1994 the HotJava web browser was introduced. It was
the first demo of interactive applets.
In March 1995, it was announced that support for Java would
be built into Netscape Navigator. And thus began the rapid
growth of Java.
What does Object Oriented
Mean?
An object is an instance of a class.
A class is a programming construct that groups together data
(properties) and functions (methods) that can be performed on
that data.
For example, consider representing a chair
Properties Methods
•Height •Create
•Width •Destroy
•Weight •Move-X
•Color •Move-Y
•X-Position •Paint
•Y-Position
Inheritance - A Powerful Tool
Inheritance allows one to build a new class that builds onto the
properties of an existing class.
Models an “is a” relationship. For example, a faculty member is
person who possesses some additional properties such as rank
or number of publications.
Inheritance keeps you from having to rewrite code. For
example, Java applets are required to have over 200 methods
but inheritance takes care of most of them.
In Java inheritance is indicated by using the extends keyword
What is Swing?
Swing is a collection of classes and interfaces
that one can use to display GUI components
or inherit from to create new components.
A calculator written using Swing
Advantages/Disadvantages of
Swing
Advantages Disadvantages
Swing is the current standard for Swing and Java 2 have limited
writing GUI components in Java 2 built-in browser support. (Only
Netscape 6.0+)
Most Swing components are
written, manipulated, and
displayed purely in Java. Plug-In for unsupported browsers
is fairly large. You can obtain the
Swing allows for a more uniform plug-in from
look and feel across platforms. It
also allows for pluggable looks. http://www.java.com/en/index.jsp
Swing supports assistive
technologies such as braille
readers
What is a Java Applet
Applets are Java programs that may be embedded
into HTML documents. The applet runs in the page as
soon as it has been downloaded.
More specifically Java applets are Java programs that
inherit the Applet (awt) or JApplet class (swing).
For examples see http://javaboutique.internet.com/
Java Applet Framework
import java.awt.*;
import javax.swing.*;
public class NameApplet extends JApplet
{
public void init()
{
// variable initializations, image loading, GUI setup, ect.
}
public void paint(Graphics g)
{
super.paint(g);
// draw graphics
}
}
Life Cycle of an Applet
The life cycle of an Applet consists of inherited functions that are called at various
times by the applet container (browser).
public void init()
{ // called when applet is first created }
public void start()
{ // called when applet is started and then restarted }
public void paint(Graphics G)
{ // invoked when screen needs to be drawn or redrawn }
public void stop()
{ //called when the user leaves the page containing the applet }
public void destroy()
{ // called when applet is permanently destroyed }
A “Hello World” Applet
import java.awt.*;
import javax.swing.*;
public class HelloApplet extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
// draw string at x=25 and y=25
g.drawString(“Hello World”, 25, 25);
}
}
Adding Applets to an HTML
Document
Insert the following where you wish the applet to appear:
<applet code=“MyApplet.class” height=“200” width=“100”>
<param name=“” value=“”> </param>
<param name=“” value=“”> </param>
<param name=“” value=“”> </param>
</applet>
Other Graphics Methods to Try
g.setFont( new Font(“Serif”, Font.BOLD, 12) )
g.setColor( new Color(0-255,0-255,0-255))
or g.setColor(Color.BLUE)
g.drawLine(start_X, start_Y, end_X, end_Y)
g.drawRect(topLeftX, topLeftY, width, height)
g.fillRect(topLeftX, topLeftY, width, height)
g.drawOval(x, y, width, height)
g.fillOval(x, y, width, height)
For more methods see the Java API documentation at http://java.sun.com
Swing GUI Components
Swing provides assorted GUI components that you can add to a
JApplet. For example,
JLabel
JTextField
JTextArea
JButton
JCheckBox
JRadioButton
Inserting a GUI Component
To insert a Swing component you must declare it
JButton myButton = new JButton(“Button1”);
and then add it to the applet’s content pane as follows:
Container container = getContentPane();
container.add(myButton, BorderLayout.NORTH);
Where the GUI component goes depends upon the LayoutManager
used by the applet.
The Border Layout Manager
Layout within an applet is controlled by a Layout manager.
The default manager is the BorderLayout Manager.
Positions are indicated by the constants BorderLayout.NORTH,
BorderLayout.WEST, BorderLayout.CENTER, etc…
A Simple Addition Applet
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AdditionApplet extends JApplet
{
// declare three text fields and a button
JTextField numOne, numTwo, answer;
JButton sumButton;
// initialize the applet and create the GUI
public void init()
{
// create the text fields
numOne = new JTextField();
numTwo = new JTextField();
answer = new JTextField();
// set the answer field to be uneditable and place default text in each field
answer.setEditable(false);
numOne.setText("Number1");
numTwo.setText("Number2");
answer.setText("Answer");
// create the button and add an actionListener to it
JButton sumButton = new JButton("Compute Sum");
sumButton.addActionListener( new SumListener() );
// add all the GUI components to the appler
Container container = getContentPane();
container.add(numOne, BorderLayout.WEST);
container.add(numTwo, BorderLayout.CENTER);
container.add(answer, BorderLayout.EAST);
container.add(sumButton, BorderLayout.SOUTH);
}
// create the private action listener class
private class SumListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int a, b, sum;
a = Integer.parseInt(numOne.getText());
b = Integer.parseInt(numTwo.getText());
sum=a+b;
answer.setText( Integer.toString(sum));
}
} // end SumListener
}
Event Handeling
Before you can handle an event you must include the import statement
import java.awt.event;
Events are handeled by adding appropriate event listeners to the
components you want to watch. For example,
JButton sum;
sum = new JButton(“Calculate Sum”);
sum.addActionListener(new SumListener());
Event listeners are objects created from a class (via new) that
implements one of the Listener interfaces. For example,
private class sumListener implements ActionListener
{ // code }
Event Handeling Cont.
Each Listener interface requires that the class implement one or
more methods that tells the computer what to do when events
occurs. For example, an ActionListener requires one to write a
actionPerformed method.
public void actionPerformed (ActionEvent event)
{ // code to handle the event }
Other event Listener interfaces include:
ItemListener
MouseListener
MouseMotionListener
KeyListener
Some Other Layout Managers
To change the change the layout manager you use the
setLayout command for the content area as follows:
Container container = getContentPane();
Container.setLayout( new LayoutManager());
You replace LayoutManager() with the desired maganger. Some
possibilities other than the BorderLayout include:
FlowLayout() - no parameters needed
GridLayout(rows, cols) - sets out a grid
CardLayout() - lays components out like cards
Addition Applet Revisited
Flow Layout
// make these changes to AdditionApplet
// add all the GUI components to the applet
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(numOne);
container.add(numTwo);
container.add(answer);
container.add(sumButton);
Grid Layout
// make these changes to AdditionApplet
// add all the GUI components to the applet
Container container = getContentPane();
container.setLayout(new GridLayout(4,1));
container.add(numOne);
container.add(numTwo);
container.add(answer);
container.add(sumButton);
Another Event Handeling
Example with CheckBoxes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBoxApplet extends JApplet
{
JCheckBox boldCheck;
int fontStyle;
// initialize the applet and create the GUI
public void init()
{
// set the size of the applet
setSize(400, 200);
// create the check box and add an ItemListener to it
boldCheck = new JCheckBox("Bold");
boldCheck.addItemListener(new myBoxListener());
// add everything to the applet
Container container = getContentPane();
container.add(boldCheck, BorderLayout.SOUTH);
}
// draw graphics
public void paint(Graphics g)
{
super.paint(g);
g.setFont(new Font("SanSarif", fontStyle, 32));
g.drawString("Java Applets are Cool", 10, 100);
}
// event handler
private class myBoxListener implements ItemListener
{
int valBold;
public void itemStateChanged(ItemEvent event)
{
if (event.getSource() == boldCheck)
{
if (event.getStateChange() == ItemEvent.SELECTED)
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
}
fontStyle = valBold;
repaint();
}
}// end myBoxListener
}// end CBoxApplet
Panels
Panels are containers that have their own layout managers and can be
added to other containers such as a slots in the applet.
To create a panel, simply declare it as follows:
JPanel myPanel = new JPanel();
To set its layout use the setLayout() method. For example,
myPanel.setLayout(new GridLayout(1,5));
To add GUI conponents to a panel, use the panel’s add method as
follows
myPanel.add(myButton);
To add a panel to an applet, add it just like any other GUI component
using the add method of the applet.
container.add(MyPanel, BorderLayout.SOUTH);
Panels Cont.
New types of panels that handle have their own components and
handle their own events can be written by inheriting from JPanel.
class myPanel extends JPanel
{
myPanel()
{ // constructor code such as setting layout and declaring and
adding GUI components
}
}
Panels use the paintComponent method instead of the paint method
and it must be called to work either directly or through repaint().
Panels Example - Calculator
GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorGUIApplet extends JApplet
{
// declare the button panel and buttons that make the calculator work
private JTextField display;
private JPanel buttonPanel;
private JButton clrButton, rParenButton, lParenButton, divideButton;
private JButton sevenButton, eightButton, nineButton, multButton;
private JButton fourButton, fiveButton, sixButton, addButton;
private JButton oneButton, twoButton, threeButton, minusButton;
private JButton zeroButton, decimalButton, powButton, equalButton;
// initialize the applet and create the GUI
public void init()
{
// create the button pannel and set its layout manager
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5,4));
// build the buttom panel one row at a time
// row 1
clrButton=new JButton("Clr");
buttonPanel.add(clrButton);
lParenButton=new JButton("(");
buttonPanel.add(lParenButton);
rParenButton=new JButton(")");
buttonPanel.add(rParenButton);
divideButton=new JButton("/");
buttonPanel.add(divideButton);
// row 2
sevenButton=new JButton("7");
buttonPanel.add(sevenButton);
eightButton=new JButton("8");
buttonPanel.add(eightButton);
nineButton=new JButton("9");
buttonPanel.add(nineButton);
multButton=new JButton("*");
buttonPanel.add(multButton);
…
// create the display area
display = new JTextField("0");
display.setEditable(false);
//add everything to the applet
Container contentPane = getContentPane();
contentPane.add(display, "North");
contentPane.add(buttonPanel, "Center");
}
}// end CBoxApplet
Simple Applet Ideas
A calculator for a desired property
Body Mass Index or Bone Density for Allied Health
Unit Conversion or PV=nRT for Physics or Chemistry
Interest Calculations for Business and Management
Quadratic formula or Pythagorean Theorem for Math
A quote of the Day Generator
- create an array of strings (string [] quoteArray = new string[100];) holding the
quotes and use a random number generator to see which string gets passed to
drawString(). The code to generate the random number is:
Random r = new Random(seedValue);
index = r.nextInt() % quoteArray.length;
Bibliography
H.M Deitel and P.J. Deitel. Java: How to Program 4th Edition.
Prentise Hall; New Jersey. 2002.
Marty Hall and Larry Brown. Core Web Programming 2nd Edition.
Prentise Hall & Sun MicroSystems Press; New Jersey. 2001.
Java 1.4.1 API documentation at http://java.sun.com/j2se/1.4.1/docs/api/
Get documents about "