【发布时间】:2013-09-03 12:26:45
【问题描述】:
我有一个 Java Applet,每次重绘 GUI 时它都会不断闪烁。大多数人看不到闪烁。其他人可以毫无问题地运行小程序,但我不行。
我不确定这是否与我重绘 UI 的方式有关,或者这是否与我的 JRE 或其他问题有关。我已经筋疲力尽地查找其他人的类似问题,但我还没有看到适用于此的答案。
我已将我正在运行的小程序缩短到相对较小的一点。这只是一艘向右移动的火箭飞船,非常简单,而且(对我而言)它不断闪烁。
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Lander extends Applet implements KeyListener,ActionListener{
Button start;
Ship s;
private static final long serialVersionUID = 1L;
public void init(){
s = new Ship(10,50);
start = new Button("START");
this.setSize(800,400);
this.setBackground(Color.black);
this.add(start);
start.addActionListener(this);
}
public void paint(Graphics g){
g.setColor(Color.LIGHT_GRAY);
g.fillRoundRect(s.getx(),s.gety(), 10, 30, 10, 10);
g.setColor(Color.GREEN);
g.fillRoundRect(s.getx()-5, s.gety()+10, 5, 20, 10, 10);
g.fillRoundRect(s.getx()+10, s.gety()+10, 5, 20, 10, 10);
}
javax.swing.Timer t = new javax.swing.Timer(30, new ActionListener(){
public void actionPerformed(ActionEvent e){
s.setx(s.getx()+2);
repaint();
}
});
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public class Ship{
int xcor,ycor;
public Ship(int x,int y){
xcor=x;ycor=y;
}
public void setx(int x){
xcor=x;
}
public void sety(int y){
ycor=y;
}
public int getx(){
return xcor;
}
public int gety(){
return ycor;
}
}
@Override
public void actionPerformed(ActionEvent x) {
if(x.getSource()==start)
reset();
t.start();
}
public void reset(){
s.setx(10);s.sety(50);
}
}
【问题讨论】:
-
1) 为什么选择 AWT 而不是 Swing?请参阅Swing extras over AWT 上的此答案,因为有很多放弃使用 AWT 组件的充分理由。如果您需要支持较旧的基于 AWT 的 API,请参阅 Mixing Heavyweight and Lightweight Components。 2) 为什么要编写小程序?如果是由于规范。老师请转至Why CS teachers should stop teaching Java applets。
-
@AndrewThompson 这实际上是我从高中编程老师那里得到的代码。这显然是他们目前正在开展的一项计划的一部分。我看了看,无法让它停止闪烁。我从未使用过或被教过使用 Applet,这也是我不熟悉这些问题的部分原因。谢谢你的资源!