【发布时间】:2018-05-17 03:26:15
【问题描述】:
我目前正在使用 Applet 类来创建一个简单的游戏。因为有闪烁效果,所以我通过创建像这样的屏幕外缓冲区为Graphics 组件添加了双缓冲:
public class AppletTest extends Applet implements Runnable {
Thread thread;
Image img;
Graphics gfx;
public final int WIDTH = 700, HEIGHT = 500;
public void init() {
this.resize(WIDTH, HEIGHT);
thread = new Thread(this);
thread.start();
img = createImage(WIDTH, HEIGHT); // off-screen buffering
gfx = img.getGraphics();
}
public void draw(Graphics g) {
gfx.setColor(Color.BLACK);
gfx.fillRect(0, 0, WIDTH, HEIGHT);
gfx.setColor(Color.WHITE);
gfx.fillRect(50, 50, 100, 100);
gfx.setFont(new Font("Century", Font.BOLD, 30));
gfx.drawString("I feel good sometimes I don't", 200, 200);
g.drawImage(img, 0, 0, this); // draws the off-screen image
}
public void update(Graphics g) {
draw(g);
}
public void run() {
while(true) {
repaint();
try {
Thread.sleep(5);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
如果您运行应用程序,所有Graphics(.fillRect、.drawString 等)组件/方法都将绘制在屏幕外缓冲区上。但是,我的目标是向小程序添加一个 JButton - 正如预期的那样,JButton 组件没有离屏加载(这意味着闪烁)。
Graphics gfx;
JButton button1;
public void draw(Graphics g) {
setLayout(null);
button1.setBounds(225, 400, 250, 50);
button1.setFont(new Font("Courier", Font.PLAIN, 17));
button1.setForeground(Color.WHITE);
button1.setBackground(Color.DARK_GRAY);
add(button1); // is it possible to draw the JButton on the off-screen buffer?
}
如何将屏幕外加载添加到 JButton 组件?
【问题讨论】:
-
Swing 组件已经是双缓冲的,问题是,您不尊重小程序绘制链(通过不调用
super.update并将其传递给您的“双缓冲”)。话虽如此,小程序已经死了 - 是时候继续前进了。更好的解决方案是从已经双缓冲的JPanel开始。然后你可以将它添加到你想要的任何容器中。另外,不要尝试“绘制” Swing 组件,除了绘制它们之外,还有很多事情要做 -
根据这个旧的 SO 帖子,JPanel 中可能仍需要双缓冲。不确定这是否有帮助,但 OP 与使用 Jpanel 时闪烁的问题相同。链接:stackoverflow.com/questions/2063607/java-panel-double-buffering
-
@KrishnanshuGupta OP(链接问题)存在闪烁问题,因为它们违反了绘画系统。如果使用正确,Swing 组件默认是双缓冲的
标签: java applet jbutton double-buffering