- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 多线程
- 示例 - Applet
- 示例 - 简单的 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用的资源
- Java - 快速指南
- Java - 有用的资源
如何使用 Java 在小程序中创建横幅
问题描述
如何使用 Applet 创建横幅?
解决方案
以下示例演示了如何使用 Thread 类播放声音使用 Applet 图像。它还使用了 Graphics 类的 drawRect()、fillRect()、drawString() 方法。
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);
}
}
结果
上述代码示例将在支持 Java 的 Web 浏览器中产生以下结果。
View in Browser.
下面是使用 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
广告