我正在使用线程来绘制一些动画,所以我需要为每一帧重新绘制标签。要做到这一点而不闪烁,我正在使用我的后缓冲图形对象更新标签(使用 lbl.update(bufferedGraphics); 方法),但是当我这样做时,标签会在 Graphics 对象的左上角重新绘制,而不是在哪里setLocation 已指定。
如何在图形中指定标签的位置,而不是在拥有标签的面板中?
这是一个SSCCE:
import javax.swing.*;
import java.awt.*;
public class LabelSSCCE extends JApplet implements Runnable {
JPanel pnl;
JLabel lbl;
Image buffer;
Graphics bufferedGraphics;
Thread t;
public void init (){
pnl = new JPanel (null);
lbl = new JLabel ();
lbl.setText ("Text");
lbl.setOpaque(true);
add(pnl);
pnl.add (lbl);
lbl.setLocation(100, 100);
lbl.setBounds (100, 100, 200, 20);
buffer = createImage (500, 500);
bufferedGraphics = buffer.getGraphics ();
t = new Thread (this, "Label");
t.start ();
}// init method
public void paint (Graphics g){
if (g != null)
g.drawImage (buffer, 0, 0, this);
}//paint
public void update (Graphics g){
paint (g);
}//update
public void render (){
bufferedGraphics.setColor (Color.WHITE);
bufferedGraphics.fillRect (0, 0, 500, 500);
lbl.update (bufferedGraphics);
update(getGraphics());
}//render
public void run (){
while (true){
try{
render ();
t.sleep (20);
} catch (InterruptedException e){
e.printStackTrace ();
}//catch
}//while
}//run
}//LabelSSCCE