Applets
Objective #1: Understand the differences between applications, applets, and apps as well as the platforms and developer tools that are used to create each one.
- In Visual Basic Programming class, we use the Visual Basic IDE and the Visual Basic programming language to create Windows applications that execute only on computers with the Windows operating system. The executable files that ended with the file extension .exe could be transported to and executed on practically any recent Windows computer (i.e. "PC"). However, those files could not be executed on other operating systems such as AppleOS or Linux or devices such as smartphones or tablets.
Many popular business and entertainment programs in the real world are Windows applications though including Halo, Internet Explorer, Microsoft Word, and many others.
It is possible to create similar Windows applications with IDE developer tools other than Visual Basic. You could use Visual C++, GNU C++, and many other free or expensive, full-featured IDE's.
- In Honors/AP Java, we use the Eclipse IDE and the Java programming language to create Windows applications that execute in the console (aka terminal) window of a Windows computer. We call these applications "console applications." With minimal changes, the same programs could be ported to run in the console window on Macintosh or Linux computers. The console window is text only but in the real-world many programs are used in console windows when graphics and interactive input devices such as touchpads and mice are not really necessary and require the code to be more bloated and buggy. The fact that Java programs can easily be modified and recompiled to execute in Windows, Linux or practically any other operating system makes Java a more portable computer language than Visual Basic or even C++. The programs that we wrote for the console window could have been upgraded with a more graphical user interface (i.e. GUI) but since the AP Computer Science exam focuses on the logic and object-oriented principles of variables, if statements, loops, method and object reusability, etc., we didn't distract ourselves with the extra overhead of having to learn Java-style textboxes, buttons, menus, etc.
- Java also allows you to create applets which are programs that can be executed inside of a web browser (e.g. Internet Explorer, Firefox, Safari, Chrome). An applet isn't a full-fledged, standalone application like Windows exe's or Java applications that are explained above. But an applet has the unique ability to be executed on practically any Windows, Mac, or Linux computer since most computers have connections to the Internet and a web browser such as Firefox installed on it. Applets can take advantage of graphical interfaces that include buttons, animation, mouse clicks, mouse drags, etc. so applet games are very popular similar to Flash games that work in web browsers. Also, you can link a Java applet to a personal web page or Facebook page so that many people can easily access it.
- In Software Design, we use the Eclipse IDE and the Java programming language to create apps that execute on any device including smartphones and tablets with the Android operating system. The company Google has created and released the Android operating system to the public in such a way that many smartphone and tablet manufacturers can install and use Android on their devices to reduce the overall costs. The apps that we create are small but graphical and interactive programs that can be distributed on a personal web page or through Android marketplaces. Note that iphone apps are created with exclusive Apple tools such as the XCode IDE (rather than Eclipse) and the Objective C computer language (rather than Java) and Apple charges developers $100/yr for the privilege of submitting apps that must be reviewed before they are listed on the one and only approved Apple Store.
Objective #2: Create a simple hello world applet
- A Java applet is a Java program that
can be executed within a web browser window (e.g. Internet Explorer) or
an applet viewer. The applet is a compiled Java .class file that resides
on a web server. When a person surfing the web visits
the applet's web page, the browser downloads the .class file which executes
within
the
browser
window.
The actual .java source file, that was compiled to create the .class
bytecode file, should not be uploaded to the web server.
- In theory, a Java applet will execute in any web
browser on any type of computer as long as a Java Virtual Machine (JVM)
has been installed on that computer. A JVM is free to download from Sun
as part of the "Java Runtime Environment" (JRE) and is often included as
part of some operating systems or web browsers. However, some versions
of Microsoft Internet Explorer do not support the JVM so you may
need
to also download the "Java Plug-in" from Sun (see java.sun.com/products/plugin
) and it may be useful to download the "Java Plug-in HTML Converter" from
Sun to be able to translater HTML pages containing <applet> tags to normal
HTML (explained below).
- Here is a simple Java applet that displays "Hello World" in an applet window:
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
super.paint(g);
g.drawString("Hello World", 50, 60 );
}
}
- A Java applet must extend the Java Applet class.
Objective #3: Create a Web page (html file) that embeds
the applet.
- It is necessary to create a web page that will embed your applet. The web page can be created by writing HTML by hand. Or, if you use JCreator as a Java IDE, it can be used to automatically create the necessary web page.
- To use JCreator's web page, create your applet by clicking File/New Project and select Java applet as the type of new project. A web page with the same name as the project will automatically be created though it will have a .htm or .html file extension.
- If typing the web page by hand, you can type the following
HTML code into a program like NotePad and save the file with a name that
ends with .html.
<applet
code="HelloWorld.class" width="500" height="300"></applet>
where the name of your compiled applet class should be substituted for "HelloWorld.class".
- The width and height attributes of the HTML applet tag can be modified to adjust the size of the applet window.
Objective #4: Use an applet's init, start, and paint methods.
- Unlike the Java applications that we programmed this school
year, there is no main method in a Java
applet. The web browser is responsible for starting the JVM, loading the applet
bytecode, and starting the applet.
- When the browser begins executing an applet these three methods are executed
in this order: init, start, and paint. These three methods can be overridden
in your applet.
- Though not required, an init method
is useful to initialize certain properties. The init method is only called
once when the applet is first loaded in the web browser for execution. Typical
actions performed here are initialization of properties and GUI components
of the applet with statements like:
setSize(600, 600);
setBackground(Color.black);
Sounds to be played are loaded here and images to be displayed
are also loaded in the init method. Threads are also created here.
You can write a constructor for an applet class and do initializations there as well as in the init method. However when the constructor is called, the size of the applet
is not available. By the time init is called, the size is known and can be used to customize the initialization according to the size. In general, it is customary to do
applet initialization in the init method.
- The start method is called after the init method completes. However the
start method is executed every time the browser returns to the applet's web
page after having viewed another web page. Typical actions performed in the
start method are to start an animation or a thread.
- Whenever the applet window needs to be drawn or redrawn,
the web browser's window manager calls the paint method.
The paint method is called when the applet is first loaded. But it is also called in less obvious situations like when a user visits another web page and then goes back to the applet's web page. A programmer should not attempt to call the paint method. If a programmer does want to forcibly redraw the applet, he should
use the repaint method with the call statement repaint();
- The paint method receives an a parameter named g that is a Graphics object.
This object stores the graphics state which includes the current color and
font as well as other drawing-related properties. The Graphics object is
part of Java's Abstract Windowing Toolkit (AWT). This is the original user
interface toolkit that Sun integrated with Java in the mid-1990's.
- The statement super.paint(g); though
technically optional in some situations, should be included as the first
statement in the paint method. There are complex situations when drawing
is mixed with GUI components that errors will occur if this statement is
overlooked.
- It is necessary to import the Java.awt.Graphics and java.applet.Applet classes in order to make use of the AWT.
- However a more modern graphical interface
called Swing is available if you import the javax.swing.JApplet class
instead of java.applet.Applet. To use Swing,
the first line of your applet would
be
public class HelloWord extends JApplet
- The following applet uses both an init method
and a paint method to display a message on
the screen
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet
{
private String message;
public void init()
{
message = "Hello World";
}
public void paint(Graphics g)
{
super.paint(g);
g.drawString(message, 50,
60 );
}
}
Objective #5: Draw shapes and place text in an applet.
- There are many interesting methods in the Graphics API that can
be used with the Graphics parameter g in
the paint method including:
- drawString
- drawLine
- drawRect
- setBackground
- setStroke
- setFont
- To draw shapes in a color other than the default
black, you can use the setColor method
to change the current color.
g.setColor(Color.red);
There are many color constants in the Color class including Color.blue and Color.green.
- It is possible to change the font that's used with
the drawString method by using the setFont method.
Font bigFont = new Font("Serif", Font.BOLD, 48);
g.setFont(bigFont);
or using an anonymous Font object
g.setFont(new Font("Serif", Font.BOLD,
48));
- You can create a standalone class that represents an object and includes
its own draw method and then instantiate objects from that class in an
applet.
import java.awt.Graphics;
public class StickMan
{
private int x;
private int y;
public StickMan(int paramX, int paramY)
{
x = paramX;
y = paramY;
}
public void draw(Graphics g)
{
g.drawLine(x, y, x, y - 20);
}
}
-----------------------------------------
import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class StickMen extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
StickMan next = new StickMan(rnd.nextInt(500), rnd.nextInt(300));
next.draw(g);
}
}
}
- See the helpful tutorial at http://www.dgp.toronto.edu/~mjmcguff/learn/java/02-drawingOtherStuff
Objective #6: Use GUI components including JLabel,
JTextField, and JButton in an applet.
- Objects that appear on an applet are called components in Java because they are child classes of the Component class.
- A JLabel object is similar
to a label in Visual Basic. It is a read-only component that usually stores
text. The setText method can be used to
change the text that is stored in a JLabel.
The getText method can be used to retrieve
the text that is stored there.
- A JTextField object is
similar to a textbox in Visual Basic. It is a one-line area where the user
can input text. It has a white background like textboxes in Visual Basic.
You can use the setText and getText methods
with a JTextField. You can also prevent
the user from inputting text into a JTextField by
using the setEditable method as in myTextField.setEditable(false);
- A JButton object is similar to a Button object in Visual Basic.
- After instantiating a components such as a JButton, you must add it to the applet's "content pane" with a statement such as
getContentPane().add(button1);
in the applet's init method.
- You may want to use a layout manager when placing objects such as JLabels
and JButtons in an applet. A layout manager controls the size and position of components in a container (i.e. applet window).
- FlowLayout - This is the default layout manager for a Panel. Components are centered with their natural size in a horizontal line. If there are too many components to fit in one row, the flow layout manager uses multiple rows. Example:
Container container = getContentPane();
container.setLayout(new FLowLayout());
container.add(new Button("Button 1"));
container.add(new Button("Button 2"));
container.add(new Button("Button 3"));
- BorderLayout - This is the default layout manager for a Window (e.g. Frame or Dialog). This layout has the following five areas -- North, South, East, West and Center. This layout is good for placing a row of buttons along one edge of the container (usually South or West).
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add("North", new Button("North"));
container.add("South", new Button("South"));
- GridLayout - This layout puts components into a grid of cells. Each cell in the grid is the same size and the components grow to fill the available area. This is good for laying out containers that look like grids. In the grid constructor below the grid is being specifed to have 2 rows with 3 columns and 5 pixels between cells. The add method places objects in order from left to right, top down.
Container container = getContentPane();
GridLayout grid = new GridLayout(2, 3, 5, 5);
container.setLayout(grid);
container.add(new JLabel("label 1 1"));
container.add(new JLabel("label 1 2"));
container.add(new JLabel("label 1 3 "));
container.add(new JLabel("label 2 1"));
container.add(new JLabel("label 2 2"));
container.add(new JLabel("label 2 3 "));
- You can create a dialog box similar to a MessageBox in Visual Basic with
JOptionPane.showMessageDialog(null, "Hello World", "Alert", JOptionPane.INFORMATION_MESSAGE);
- See this helpful tutorial about layout managers at http://www.javacoffeebreak.com/java108/java108.htm
- See the examples at the bottom of this page http://www.javacoffeebreak.com/java107/java107.html
Objective #7: Work with mouse inputs in an applet.
- In order to allow the user to click buttons in
an applet you must implement the ActionListener interface
and attach listeners to your JButton objects (or any other object
that is capable of receiving
a mouse event). The first line of your applet class will look like this
public class Demo extends JApplet implements ActionListener
Then you would use this line of code in your init method to attach a Listener
object to a JButton named button1.
button1.addActionListener(this);
The keyword this refers to the applet class
itself.
You must override the actionPerformed method that comes from the ActionListener class. Here is where you would write code that executes if the button is
clicked
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button1)
{
label.setText("Hello World");
}
}
The code segment above detects that the JButton named button1 was clicked (i.e.
the button was the source of the ActionEvent parameter) and displays the phrase
"Hello World" in a JLabel object named label.
- You can also implement the MouseListener interface
to detect mouse clicks in the applet window. However you must then implement the methods mousePressed, mouseReleased,
mouseClicked, mouseEntered, & mouseExited. Here is an example that overrides
mousePressed but leaves the other methods empty...
public void mousePressed(MouseEvent event)
{
String input = JOptionPane.showInputDialog("Enter your name");
label.setText(input);
repaint();
}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
Notice that even if you don't want to put any code into the mouseReleased method, you must still implement it as an empty method.
- See the helpful tutorial at http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput
- A list of interesting mouse events can be found at http://www.javacoffeebreak.com/java107/java107.html
Objective #8: Work with keyboard inputs in an applet.
- You can use the JOptionPane.showInputDialog method to accept user inputs
into an applet just like we did in a previous chapter.
- You can also accept user input into a JTextField.
- You can use the Double.parseDouble and Integer.parseInteger methods
to convert string inputs into primitive int and double values
for mathematical processing. The following code segment adds PA sales tax
to a purchase
String userInput = textField.getText();
double userNum = Double.parseDouble(userInput);
double withTax = userNum * 1.06;
textArea.setText(new Double(withTax).toString());
- You can also implement the KeyListener interface to detect key presses. The first line of your applet class would be something like:
public class Demo extends JApplet implements KeyListener
and you have to override the methods keyPressed, keyReleased, & keyTyped. You can use the KeyEvent class's getKeyText and getKeyCode methods to detect what key was pressed as in the keyPressed or keyReleased methods:
public void keyPressed(KeyEvent event)
{
outputMessage = "Key pressed: " + event.getKeyText(event.getKeyCode());
}
- You can also react according to which key was pressed using getKeyChar in the implementation of the keyTyped method as in...
public void keyTyped(KeyEvent key)
{
char letter = key.getKeyChar();
if (letter == 'a')
{
// do something here in response to the user's press of the letter 'a'
}
}
- In order to make sure that the applet responds to key presses at the very beginning of its execution, add the statement
requestFocus();
to the beginning of the paint method.
- See the helpful tutorial at http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput
Objective #9: Display an image file in an applet.
- Use an applet's getImage method
to load an Image object in the init method:
Image imageFile = getImage(getDocumentBase(), "picture.gif");
getDocumentBasemethod returns the path of the Web page (i.e. html file). The image file must be located in the same directory as that file. Alternately, the getCodeBase() method can be used to return the path of the applet's compiled code (i.e. .class file). There should be no spaces in the filename of the graphic (e.g. picture.gif in the example above).
- In the applet's paint method
use the following statement to display the image
g.drawImage(imageFile, x, y, this);
where the top left corner of the image will be placed at (x, y).
Objective #10: Play an audio file in an applet.
- In order to play sound in an applet, it's best to use an AudioClip. Add the import statement import java.applet.AudioClip; to the top of your file.
- The statement
AudioClip sound = getAudioClip(getDocumentBase(), "sound.au");
will load the audio file named sound.au. (It's best to practice with sound files with the .au file extension. It can be difficult to get some .wav sound files to work with applets since files compressed using ADPCM or other compression schemes may not work. The Java Sound engine supports only linear PCM audio files.)
- The statement sound.play(); will play the audio clip. The statement sound.stop(); will stop the audio clip and the statement sound.loop(); will cause it to loop continuously until the stop method is executed.
- Instead of importing java.applet.AudioClip and using an AudioClip object as described above, you can simply use the applet class play method to play an audio clip like this
play(getDocumentBase(), "sound.au");
but after it is played one time, the clip is marked for garbage collection. Using the AudioClip object method allows the sound to be repeated multiple times since it is "attached" to the AudioClip object.
- See http://www.cs.princeton.edu/introcs/faq/mp3/mp3.html for how to play an MP3 file in Java using JLayer from javazoom.net. You can also make music with MIDI in Java using JMusic. See http://jmusic.ci.qut.edu.au/.
Objective #11: Create animation in an applet.
- Animation can't be performed by simply placing a g.drawImage statement inside of a loop in the paint method. However, Timer objects or threads can be used to perform animation. Within a thread's run method or a Timer's actionPerformed method, you can update an object's position and repaint the object in the new position.
- In the case of using a thread, the animation loop keeps track of the current frame and calls the method repaint to update the screen. A thread allows other processes within the applet and on the computer itself execute at the same time (or at least appear that they are executing at the simultaneously). You need to implement the Runnable interface to create a thread. Swing is not considered to be thread-safe so you must use import java.applet.*; rather than import javax.swing.*; . See the helpful tutorial on threads at http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads
- Using one of these techniques, you may see flickering or a flash. This is due to the the problems that the computation for repainting each frame takes too long and that the entire background is cleared before paint is called. While the computation of the next frame occurs you are seeing the background of the animation. To reduce the flickering, you can use the update method and/or you can use backbuffering.
- update method - By default, the update method clears the applet's background and then calls the paint method. By overriding the update method, you can draw over only the area that needs to be refreshed avoiding having the applet's entire background to be cleared each time repaint is called.
- backbuffering - With backbuffering (aka double-buffering), you draw a frame into an offscreen image and then place the entire image onto the screen with one call to a method. Since the drawing is done offscreen, this is more efficient than painting new frames directly to the screen.
- See the helpful tutorial on backbuffering athttp://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer
- To accumulate drawing operations for more interesting animation, see the helpful tutorial at http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting