Getting Started

Download Report

Transcript Getting Started

Java Applets
Getting Started
Import Files
• In order to run the applet properly, we
have to import some files into our class.
These files are:
– import java.applet.*;
– import java.awt.*;
• These lines of code would be placed
before the class declaration.
Declaring the Main Class
• The standard class declaration looks
something like:
public class ClassName {
• Declaring an applet class is not much
different. It looks like this:
public class ClassName extends Applet{
Methods Involved
• Inside Main you should make 5 different
methods:
– init
– start
– stop
– destroy
– paint
public void init( )
• This method initializes the applet. This is
where you generally choose the applet color.
It would look something like:
public void init( )
{
setBackground(Color.white);
}
• White could be substituted with black, blue,
red, gray, darkGray, pink, yellow, green, cyan,
lightGray, magenta and orange.
public void start( )
• This is where you would control your
thread. For now we are focusing on the
basic ideas of an applet, so we will get to
threads later. As for the time being, just
declare it in your applet:
public void start( ) { }
public void stop( )
• Don’t worry about this method for the
basics. Just declare it in your code:
public void stop( ){ }
• The only thing you might use this method
for would be to include “threadName.stop(
)” which would stop that thread from
running.
public void destroy( )
• This method would only be included if you
wished to publish your applet to the
internet. This would close the applet if you
closed the web browser rather than
leaving the applet. For now I wouldn’t
worry about it though.
public void paint(Graphics g)
• This is the method that will get the most
use. It takes the parameter g from class
Graphics. You will always use this
parameter. The methods within class
Graphics that you will use most are:
– g.setColor(Color.white);
– g.drawString(“text”, x, y);
• x and y represent the location of the string.
public void paint(Graphics g)
• A sample method would look like:
public void paint(Graphics g)
{
g.setColor(Color.white);
g.drawString(“Hello World!”, 70, 100);
}
• Once again, white could be substituted
with a color of your choosing.
Sample Applet
import java.applet.*;
import java.awt.*;
public class MyFirstApplet extends Applet
{
public void init( )
{
setBackground(Color.black);
}
public void start( ) { }
public void stop( ) { }
public void paint(Graphics g)
{
g.setColor(Color.white);
g.drawString("Hello world!", 70, 100);
}
}
The code would generate:
The End
• That is how you would get a standard Java
Applet to work properly.