所以我在下面有这个代码,我正在尝试刷新屏幕上的文字以显示当前时间。到目前为止,我已尝试使用drawRect
作为清除方式,但文本将保留在那里,而不是更新。 super.paint
也没有用。同样,我会将这个新语句合并到init()或paint()方法中吗?
import java.awt.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.geom.*;
public class HelloWorldApplet extends javax.swing.JApplet {
Calendar now = Calendar.getInstance();
int second = now.get(Calendar.SECOND);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
String greeting;
String currentTime = ("The time currently is: " + hour + ":" + minute + " and" + second + " seconds");
String currentDate = ("Date: " + month + "/" + day + "/" + year);
public void init() {
greeting = "Hello World";
Font myFont = new Font("TimesRoman", Font.BOLD, 20);
// set the component or graphics object like this:
setFont(myFont);
}
public void paint(Graphics screen){
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString(greeting, 20, 50);
screen2D.drawString(currentTime, 20, 75);
screen2D.drawString(currentDate, 20, 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//DoNothing. Pretend it didnt happen...
}
}
public void setup(Graphics screen) {
for (int x = 1; x < 2000000000;) {
x++;
repaint();
}
}
}
答案 0 :(得分:2)
@trashgod已经解释了最重要的事情,但我会在答案中重复一遍,以便更完整
paintComponent()
,而不是paint()
paintComponent()
方法获取时间,或者它始终保持不变super.paintComponent()
以清除屏幕所以这是固定代码:
import java.awt.*;
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class HelloWorldApplet extends javax.swing.JApplet {
String greeting;
Font myFont = new Font("Times New Roman", Font.BOLD, 20);
public void init() {
greeting = "Hello World";
add(new MyPanel());
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
class MyPanel extends JPanel {
public void paintComponent(Graphics screen) {
super.paintComponent(screen);
Calendar now = Calendar.getInstance();
int second = now.get(Calendar.SECOND);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
String currentTime = ("The time currently is: " + hour + ":" + minute
+ " and " + second + " seconds");
String currentDate = ("Date: " + month + "/" + day + "/" + year);
setFont(myFont);
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString(greeting, 20, 50);
screen2D.drawString(currentTime, 20, 75);
screen2D.drawString(currentDate, 20, 100);
}
}
}