Java applets
- embedding Java applications into webpages
- simulations, tutorials, web interfaces
applet example
- copy Java code to file AppletDrawingLines.java
- run the Java compiler
javac AppletDrawingLines
- copy html code to file anything.html
- open the html file with a browser
firefox anything.html
,
sometimes you need a reload
import javax.swing.*; // for JApplet, ..
import java.awt.*; // for Color
import java.util.*; // for sleeping
/** Java applet example based on Japplet.
* Has no main() function, init() executed before paint().
*/
public class AppletDrawingLines extends JApplet {
int width, height; // size of the html applet box
public void init() { // executed when the applet starts
width = getSize().width; // getSize() is a member function of JApplet
height = getSize().height; // returning the size of the html applet box
setBackground(Color.black);
}
/** The .pain() function is executed whenever the applet is
* asked to redraw itself.
*/
public void paint(Graphics g) {
g.setColor(Color.green);
for (int i=0; i<10; i++)
{
g.drawLine(width, height, i * width / 10, 0);
// drawLine(x-start,y-start,x-end,y-end)
try {
Thread.sleep(700); // sleep for a short time
} catch (InterruptedException e) {
System.out.println(e.toString());
}
} // end of loop over drawing lines
} // end of AppletDrawingLines.paint()
} // end of AppletDrawingLines
- html code for embedding applet
- html tags are like brackets:
<center>...</center>
<html>
<head>
<meta charset="utf8" />
<title>Java applets</title>
</head>
<!-- this is a comment: a html page has a header and a body -->
<body>
<center>
<h1>Embedded Java applet</hr>
<br><br>
<applet width=400 height=400 code="AppletDrawingLines.class"> </applet>
</center>
</body>
</html>
Mouse events
- here
Applet
instead of JApplet
and java.awt
instead of javax.swing
- the interfaces
MouseListener
and MouseMotionListener
are implemented,
all their member functions need to be explicitly declared, even when void
import java.applet.*; // this example with Applet instead of JApplet
import java.awt.*;
import java.awt.event.*;
public class AppletMouseFollow extends Applet
implements MouseListener, MouseMotionListener {
int width, height; // size of html applet box
int mx, my; // the mouse coordinates
boolean isButtonPressed = false;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground(Color.black);
mx = width/2; // starting position of
my = height/2; // square
addMouseListener( this ); // adding event listeners
addMouseMotionListener( this );
}
/** Called when the pointer enters the applet's box.
* All functions of the implemented interfaces
* MouseListener and MouseMotionListener need to be implemented.
*/
public void mouseEntered( MouseEvent e ) {
setBackground(Color.blue);
}
public void mouseExited( MouseEvent e ) {
setBackground(Color.orange);
}
/** Called after a press and release of a mouse button
* with no motion in between.
* If the user presses, drags, and then releases,
* there will be no click event generated.
*/
public void mouseClicked( MouseEvent e ) {
setBackground(Color.cyan);
}
/** Called when mouse down but not released.
*/
public void mousePressed( MouseEvent e ) {
isButtonPressed = true;
setBackground(Color.gray);
repaint(); // re
// "Consume" the event so it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
/** Called when released after drag.
*/
public void mouseReleased( MouseEvent e ) {
isButtonPressed = false;
setBackground(Color.black);
repaint();
e.consume();
}
/** Called during motion when no buttons are down.
*/
public void mouseMoved( MouseEvent e ) {
mx = e.getX(); // the mouse events provides the current
my = e.getY(); // mouse position
showStatus( "Mouse at (" + mx + "," + my + ")" ); // browser status line
repaint(); // calls the paint() method
e.consume();
}
/** Called during motion with buttons down.
*/
public void mouseDragged( MouseEvent e ) {
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}
public void paint( Graphics g ) {
if (isButtonPressed)
g.setColor(Color.black); // black rectangle if moused down
else
g.setColor(Color.gray); // gray otherwise
//
g.fillRect(mx-20, my-20, 40, 40); // filled and centered rectangle
}
} // end of AppletMouseFollow
Bouncing with and without threads
- try to to change speed while bouncing
- double buffering
for professional applications, avoiding flickering:
paint first everything offscreen and then upload
full graphics (not done here)
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/** A class can extend only a single parent class
* but it can implement any number of interfaces.
*/
public class AppletBounce extends Applet
implements ActionListener, AdjustmentListener, Runnable
{
private int width, height; // width, height of applet box
private int tick = 100; // length of pausini, speed control
private int initialY = 70; // bouncing between these
private int lowestY; // two values
private Button goThreaded = new Button("go threaded");
private Button goNotThreaded = new Button("go not threaded");
private Scrollbar speed =
new Scrollbar(Scrollbar.HORIZONTAL,tick,30,20,400);
/** Called when applet is loaded.
*/
public void init() {
setBackground(new Color(230,230,230));
width = getSize().width;
height = getSize().height;
lowestY = (int)(height*0.8); // use relative units
// --- select layout manager
setLayout(new BorderLayout()); // a layout manger
Panel buttons = new Panel(); // a seperate panel for the buttons
// --- button for starting animation with current thread
goNotThreaded.setBackground(Color.lightGray);
goNotThreaded.addActionListener(this);
buttons.add(goNotThreaded);
// --- button for starting animation in an additional thread
goThreaded.setBackground(Color.lightGray);
goThreaded.addActionListener(this);
buttons.add(goThreaded);
add("North", buttons); // add both bottoms to the top
// --- the Scrollbar 'speed' is inside the Panel 'speedControl'
Panel speedControl = new Panel();
speedControl.setBackground(Color.lightGray);
speed.setPreferredSize(new Dimension((int)(width*0.6),20));
speedControl.add(new Label("faster",Label.RIGHT));
speedControl.add(speed);
speed.addAdjustmentListener(this);
speedControl.add(new Label("slower"));
add("South", speedControl); // add the speed-control bar to the bottom
} // end of AppletBounce.init()
/** Catch scrollbar event.
*/
public void adjustmentValueChanged(AdjustmentEvent e) {
tick = speed.getValue();
}
/** Catch button events.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == goThreaded) // the new Thread calls run()
new Thread(this).start(); // running the object 'this'
if (e.getSource() == goNotThreaded) // calling directly
doAnimation(); // doAnimation()
}
/** AppletBounce is implementing runnable and run() is
* called when a new thread is started.
*/
public void run() {
doAnimation();
}
/** Let a ball at random position x bounce downwards
* and upwards, with increasing speed (step).
*/
public void doAnimation() {
// --- setup of bounds
int minX = (int)(width*0.1); // allways use
int maxX = (int)(width*0.9); // relative units
int x = (int)(minX+Math.random()*(maxX-minX)); // fixed random x for bouncing
int y = initialY; // variable y of bouncing
int step = 1; // (in)decrement for y
// --- setup of graphics
Graphics g = getGraphics();
Color background = getBackground(); // needed for repainting
g.setColor(Color.black);
g.drawLine(minX, lowestY+20, // bottom line
maxX, lowestY+20);
// --- bouncing downwards
while (y <= lowestY) {
g.fillOval(x, y, 20, 20); // paint ball
pause(tick); // pause animation method
g.setColor(background);
g.fillOval(x, y, 20, 20); // turn ball to background
g.setColor(Color.black);
y = y+step;
step++;
}
// --- hitting bottom
g.setColor(new Color(204,51,51));
g.fillOval(x, lowestY, 20, 15); // extra image for lowest point
g.drawString("boing!",x-10,lowestY+35); // its 'boing'
pause(tick*3); // pause for reading
g.setColor(background);
g.drawString("boing!",x-10,lowestY+35);
g.fillOval(x, lowestY, 20, 15); // erase the extra squeeze ball
// --- bouncing upwards
g.setColor(Color.black);
while (step>0) {
step--;
y = y-step;
g.fillOval(x, y, 20, 20);
pause(tick);
g.setColor(background);
g.fillOval(x, y, 20, 20);
g.setColor(Color.black);
}
} // end of AppletBounce.doAnimation()
/** Just a wrapper for the exception capture.
*/
private void pause(int pauseLength) {
try { Thread.sleep(pauseLength); } catch (InterruptedException e) {}
}
} // end of AppletBounce