Applets - Java Programming for the Web

advertisement
Applets - Java Programming for the Web
An applet is a Java program designed to run in a Java-enabled browser or an applet viewer. In a browser, an applet is called into
execution when the APPLET HTML tag is encountered by the browser while it is executing the HTML script for the Web page. The
APPLET tag refers the browser to a Java class file that it will find in the same directory as the HTML script file for the Web page.
The Java class file is the compiled “bytecode” for the applet. Virtually any code can be run in an applet. The main exceptions, for
security purposes, is that an applets cannot read or write to any local resource. An example of an Applet tag embedded in an HTML
script would look like:
<html>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
HTML syntax requires a TAG (such as APPLET)enclosed in < > with its resource description(s) followed by the same named TAG
with a preceding /. The minimum TAGs for a HTML script is HTML and BODY
.
The Applet class is a subclass of Panel which is a subclass of Container. Unlike the Frame class, the Panel class does not create a
separate window of its own. Since Panel is a container, we can add any of the AWT or Swing objects to it. The Applet class has
many methods, but the most important ones are:
init() – called, after construction of the applet, by the browser or applet viewer to inform this applet that it has been loaded into the
system. It is always called once, before the first time that the start method is called.
start()- called when the browser opens the applet’s window. It is called after the init method and each time the applet is revisited
in a Web page.
stop()- called when the browser changes to a new page, making the applet temporarily hidden.
destroy()- called when the applet exits, reversing actions taken by init().
Applets use the Graphics class to provide color and other graphics attributes to its Panel parent. The method paint() of the Graphics
class is overridden to provide graphic information. It applies methods to the Graphics object that it receives as a parameter. The
method is never called because it is automatically called by the window manager. An example of overriding the paint() method in
an Applet follows:
public class Einstein extends java.applet.Applet
{
//----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.
//----------------------------------------------------------------public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40);
// square
page.drawRect (60, 80, 225, 30);
// rectangle
page.drawOval (75, 65, 20, 20);
// circle
page.drawLine (35, 60, 100, 120); // line
page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}
The above Applet produces the following graphics:
The steps for creating and running an Applet in NetBeans are:
1. File – New Project
2. General – Java Class Library-Next
3. Type Project name and location and click Finish
4. In Projects subwindow, right click ProjectName
5. New-File/Folder-Java Classes-Applet(or JApplet)-Next
6. Type Applet Class name and Project name, click Finish
7. Type or Cut and Paste your code into the Applet Body.
8. To Compile the code, Right click on the ProjectName and choose Build Project
9. To Run the Applet in the AppletViewer: Right Click on the Applet.java name (under Source Packages)
10. Click Run File.
The example above is very basic. If the Applet wants to do any logical, arithmetic, or GUI processing, it must make use of the init and
start methods. The init method acts like the constructor for the Applet. You use it to create objects need by the Applet. In the next
example we create a panel that will calculate compound interest on an amount input by the user. This panel is created in the init()
method. It uses several Java objects, JTextField, JLabel, JButton, JPanel, and a generic JComponent to create the look of the
calculator illustrated below:
p
p1
p2
canvas
p3
pane
p4
The code to generate the Applet calculator panel above follows:
public class CalcInt extends JApplet
{
JTextField getRate = new JTextField(5);
JTextField getBalance = new JTextField(8);
JTextField getYears = new JTextField(3);
JLabel rate = new JLabel("Rate");
JLabel balance = new JLabel("Balance");
JLabel years = new JLabel("Years");
MyCanvas canvas
= new MyCanvas();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p = new JPanel();
JButton amount
= new JButton("Amount");
JButton clear = new JButton("Clear");
String command = " ";
String prompt = "Enter Data and Press Button ";
NumberFormat nf;
public void init()
{
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
p1.setLayout(new GridLayout(2,1));
p1.add(rate);
p1.add(getRate);
p2.setLayout(new GridLayout(2,1));
p2.add(balance);
p2.add(getBalance);
p3.setLayout(new GridLayout(2,1));
p3.add(years);
p3.add(getYears);
p.setLayout(new FlowLayout());
p.add(p1);
p.add(p2);
p.add(p3);
amount.setMnemonic('A');
amount.setToolTipText("Calculate Amount");
p4.setLayout(new GridLayout(1,2));
p4.add(amount);
p4.add(clear);
amount.addActionListener(canvas);
clear.addActionListener(canvas);
pane.add(p);
pane.add(canvas);
pane.add(p4);
canvas.setPreferredSize(new Dimension(100,100));
nf = NumberFormat.getCurrencyInstance();
}
Each panel p1, p2, and p3 is created with a label and textfield and then put into panel p(the entire upper section). The buttons are put
into panel p4 with listeners added. Then p, canvas, and p4 are put into pane to complete the content. This example also illustrates the
use of the setMnemonic()method, allowing an ALT+Letter to activate the Button, and the setToolTipText()method which
provides mouse rollover textual feedback for the Button.
Threads
Threads are used to provide independent sequences of processing steps to executed concurrently( the processor splits its time
processing between steps in each Thread. Each method has its own thread for its own steps, however a new Thread can be created and
started that becomes a new independent sequence. Many animations use Threads, especially if they are displaying images that do not
require any user interaction. The Thread class implements the Runnable interface and has many methods, but the most important
ones are:
start()- called when the Thread is to begin execution.
run()- called after start is executed. It is the body of the Thread, it begins after start is called and executes until it reaches a return,
or when the stop method is called.
However, stop() method has been found to be unstable and has been deprecated, so now, Threads are dereferenced when they need
to be stopped. The following illustrates an Applet that uses a Thread to animate a String of Text on the Screen. The text is redrawn a
successive locations within the Applet’s screen area. This Applet also illustrates the use of the getToolkit()and
getScreenSize() methods to obtain available screen size info from the hardware platform. This Applet uses the entire screen for
the scrolling area, so, maximize the AppletViewer window when you test run it. Also note that the Applet must use the Runnable
interface if it needs to create a Thread object.
public class ScrollingString extends Applet implements Runnable
{
Thread theThread;
Font myfont;
FontMetrics fontmet;
String str="The Last Java Example";
boolean loop = true;
int strWidth;
int xpos;
int ypos;
int winWidth;
public void init()
{
myfont = new Font("TimesRoman",Font.BOLD,22);
fontmet = getFontMetrics(myfont);
strWidth = fontmet.stringWidth(str);
Toolkit tools = this.getToolkit();
Dimension size = tools.getScreenSize();
winWidth=size.width;
ypos = (size.height/2 - fontmet.getHeight());
ypos=ypos+fontmet.getHeight();
setBackground(Color.white);
}
public void start()
{
if (theThread==null)
{
theThread=new Thread(this);
theThread.start();
}
}
public void run() //this method belongs to the Thread
{
while (loop)
{
for (int i=winWidth; i>0-strWidth; i--)
{
xpos=i;
repaint();
try {theThread.sleep(10);}
catch (InterruptedException e) {}
}
}
}
public void stop()
{
if (theThread!=null)
{
loop=false;
theThread=null;
}
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.setFont(myfont);
g.drawString(str,xpos,ypos);
}
}
For other ways a Thread can be created and used in an application, see the Threads Javadocs .
See/run Einstein, CalcInt, and ScrlStr project folders in the Instructors folder.
Download