夜光序言:
“你喜欢、这个世界吗?”
“无关喜欢,只是早就已经放弃了。”
——因为世界放弃了他,所以他只能放弃世界。
正文:程序的魅力~~
package com.Genius.Applet;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
/*夜光:Applet也具有Java的跨平台性
* 我们写一个程序,使得字体变大
* */
public class Demo01 extends Applet implements Runnable{
private Image image;
private Graphics graphic;
private Font font;
private String str;
private Thread thread;
private int fontSize;
public void init(){
this.setSize(400,400);
image = createImage(400,400);
graphic = image.getGraphics();
str = "这是Applet小程序";
font = new Font("TimesRoman",Font.BOLD,8);
}
public void start(){
if(thread == null)
{
thread = new Thread(this);
thread.start();
}
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
graphic.setColor(Color.black);
graphic.fillRect(0, 0, getSize().width, getSize().height);
font = new Font("TimesRoman",Font.BOLD,fontSize);
graphic.setColor(Color.white);
graphic.setFont(font);
FontMetrics fm = graphic.getFontMetrics(font);
int fontHeight = fm.getHeight();
int w;
int baseLine = getSize().height/2+fontHeight/2;
w = fm.stringWidth(str);
w = (getSize().width - w)/2;
graphic.drawString(str, w, baseLine -=20);
g.drawImage(image, 0, 0, this);
fontSize++;
}
public void run(){
while(true){
repaint();
if(fontSize > getSize().height)
fontSize = 0;
try{
thread.sleep(100);
}catch(InterruptedException e){
}
}
}
}
package com.Genius.Applet;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
/*夜光:这里我们使用Applet和多线程来
完成一个模拟灯光的效果
为文字设置一个底色,然后用白色模拟灯光
被照到的部分会变成白色*/
public class Demo02 extends Applet implements Runnable{
private String text;
private Font font;
private int fontSize;
private Thread thread;
private int position = 100; //夜光:声明光标点生成位置
private int tsize = 20;
private int twidth = 0;
private int fheight,baseLine,w;
public void init(){
text = "灯光艺术字";
fontSize = 39;
font = new Font("TimesRoman",Font.BOLD,fontSize);
//创建Font对象
FontMetrics fm = getFontMetrics(font);
//获取FontMetrics字体规格对象
fheight = fm.getHeight();
position = w;
setBackground(Color.black);//夜光:设置小程序的背景色为黑色~~
}
public void start(){
if(thread == null){
thread = new Thread(this);//创建多线程
thread.start(); //启动多线程
}
}
public void stop()
{
thread.stop();
thread = null;
}
public void run() // 夜光:运行线程
{
while(true){
repaint(); //重绘此组件
try{
thread.sleep(30);
}catch(InterruptedException e){
}
}
}
public void update(Graphics g){ //夜光:更新组件
paint(g);
}
// 夜光:利用clipRect()方法, 每次调用显示方法paint()时
// 先用红色的笔画一遍文字,再用白色在裁剪区画一遍文字
public void paint(Graphics g){
g.setFont(font);
g.setColor(Color.red);
g.drawString(text, w, baseLine);
g.clipRect(position, 0, tsize, getSize().height);
g.setColor(Color.white);
g.drawString(text, w, baseLine);
position = (position+1) % (twidth +100);
}
}