我已经开始制作粘液排球了。我遇到了这个问题,其中粘液角色的图像疯狂地闪烁。图像消失的时间大约相同。
我尝试删除super.paint(g);在paint方法中修复了闪烁问题,但是它创建了一个新问题,不能从以前的位置删除图像。
源代码:
package slimevolleyball.main;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static int x = 275;
public static int y = 300;
public static boolean right = false;
public static boolean left = false;
public static boolean jump = false;
public static int startjump = 0;
public static int low = 300;
public static double gravity = 0;
public static double time = 0;
public static int startVelocity = 0;
public static double velocity = 0;
public static BufferedImage slime1;
public static BufferedImage slime2;
public static BufferedImage background;
static Rectangle FrameSize;
static JFrame frame = new JFrame();
public Main() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
}
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
if (jump == false) {
jump = true;
startjump = 1;
}
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
left = true;
right = false;
break;
case KeyEvent.VK_RIGHT:
right = true;
left = false;
break;
}
}
});
setFocusable(true);
setTitle("Slime VolleyBall");
setSize(600, 400);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(slime1, x, y, null);
}
public static void main(String[] args) throws InterruptedException, IOException {
Main game = new Main();
slime1 = ImageIO.read(new File("red.png"));
while (true) {
MoveSlime1();
Update();
game.repaint();
Thread.sleep(2);
}
}
private static void Update() {
FrameSize = frame.getBounds();
}
private static void MoveSlime1() {
if (right == true && x <= FrameSize.getWidth() / 2) {
x += 1;
} else if (left == true && x >= 0) {
x -= 1;
}
if (jump == true) {
if (startjump == 1) {
low = 300;
gravity = -9.8;
time = 0;
startVelocity = 3;
velocity = 0;
startjump = 0;
} else {
velocity = startVelocity + (gravity * time);
y -= velocity;
time += 0.005;
if (time > 0.01 && y >= low) {
jump = false;
}
}
}
}
}
答案 0 :(得分:4)
JFrame
不是双缓冲的,因此是闪烁,这只是为什么你不应该从JFrame
延伸并覆盖它paint
的一个原因之一方法
相反,将所有逻辑移到一个扩展JPanel
的类,然后覆盖它的paintComponent
方法,这样,您就可以免费获得双缓冲。< / p>
此外,您应该避免使用KeyListener
并使用Key Bindings API来解决KeyListener
另外,static
不是你的朋友,你应该学会在没有它的情况下生活