我尝试过以下代码。请指导我哪里错了???期望的输出就像...... 米(延迟)E(延迟)S(延迟)S(延迟)一(延迟)克(延迟)即
import java.util.*;
import java.applet.*;
import java.awt.*;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends Applet implements Runnable {
Thread t;
//char msg[] ={"m","e","s","s","a","g","e"};
String str = "message";
Graphics bufferg;
Image buffer;
int counter=0,x=str.length(),i=0;;
public void init() {
//initializa the thread
t = new Thread(this);
t.start();
Dimension d = getSize();
buffer = createImage(d.width,d.height);
}
public void run() {
try {
while(true)
{
//requesting repaint
repaint();
if(counter==x)
{
Thread.sleep(200);
counter=0;
i=0;
}
else
{
Thread.sleep(400);
}
}
}
catch(Exception e) {
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(bufferg == null) {
Dimension d = getSize();
bufferg.setColor(Color.green);
g.setFont(new Font("Comic Sans MS",Font.BOLD,36));
bufferg.drawString(str.charAt(i)+"",20,20);
counter++;
i+=1;
//update screen
g.drawImage(buffer,0,0,this);
}
}
}
我正在处理命令提示符,它给了我一堆不同的错误。我想知道为什么如果有人能通过尝试解释我的错误。提前完成。
答案 0 :(得分:0)
我发现的问题包括:
使用JApplet而不是Applet。
在init方法中,在启动线程之前创建缓冲区。
使用run方法中的字母更新缓冲区。油漆方法只是油漆。没有计算。
这是工作代码。我将代码格式化为Eclipse,这是一个用于Java开发的集成开发环境(IDE)。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends JApplet implements Runnable {
private static final long serialVersionUID = 1722008447683646619L;
Thread t;
String str = "message";
Image buffer;
@Override
public void init() {
Dimension d = getSize();
buffer = createImage(d.width, d.height);
// Initialize the thread
t = new Thread(this);
t.start();
}
@Override
public void run() {
int x = 40;
int y = 40;
for (int i = 0; i < str.length(); i++) {
Graphics g = buffer.getGraphics();
g.setFont(new Font("Comic Sans MS", Font.BOLD, 36));
g.setColor(Color.GREEN);
g.drawString("" + str.charAt(i), x, y);
g.dispose();
x += 40;
repaint();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
}