- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to create a banner using Applet in Java
Problem Description
How to create a banner using Applet?
Solution
Following example demonstrates how to play a sound using an applet image using Thread class. It also uses drawRect(), fillRect(), drawString() methods of Graphics class.
import java.awt.*;
import java.applet.*;
public class SampleBanner extends Applet implements Runnable {
String str = "This is a simple Banner ";
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
}
catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}
}
Result
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
The following is an another sample example to create a banner using Applet.
import java.awt.*;
import java.applet.*;
public class NewApplet extends Applet implements Runnable {
String msg = " It is a moving Banner. ";
char cha;
boolean stopFlag = true;
Thread t = null;
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
public void run() {
for(;;) {
try {
repaint();
Thread.sleep(250);
cha = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg = msg + cha;
if(stopFlag) break;
}
catch(InterruptedException e) {}
}
}
public void stop(){
stopFlag = true;
t = null;
}
public void paint(Graphics g) {
g.drawString(msg,60,30);
}
}
java_applets.htm
Advertisements