package local.ryan.grid;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Game implements Runnable, KeyListener {
public boolean isRunning = false;
private long lastTime;
private double fps;
public int gamestage = 0;
public int width = 300, height = 300;
public String title = "Le Go!";
public JFrame frame = new Frame(2, width, height, title);
public int x = 0, y = 0, velX = 0, velY = 0;
public static void main(String[] args) throws InterruptedException {
Thread game = new Thread(new Game());
game.start();
}
public void run() {
frame.addKeyListener(this);
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(false);
start();
while(isRunning) {
lastTime = System.nanoTime();
try {
// Limit Each Frame, to 60 fps.
// Prevents performance issues with multiple objects.
Thread.sleep(1000/60); // 1000 miliseconds (1 second)/60 frames-per-second ~ 17 ms.
} catch (InterruptedException e) {
e.printStackTrace();
}
render(frame.getGraphics());
fps = 1000000000D/(System.nanoTime() - lastTime); //one second(nano) divided by amount of time it takes for one frame to finish
lastTime = System.nanoTime();
// Change to integer, to remove decimals.
System.out.println("FPS: " + (int) fps + ".");
}
}
public void render(Graphics c) {
c.clearRect(0, 0, width, height);
Graphics2D g = (Graphics2D)c;
g.setColor(Color.RED);
g.fillRect(x, y, 30, 60);
g.dispose();
}
public void start() {
if(isRunning)
return;
isRunning = true;
}
public void stop() {
if(!isRunning)
return;
isRunning = false;
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_D) {
velX += 1;
actionPerformed();
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public void actionPerformed() {
x = x + velX;
y = y + velY;
render(frame.getGraphics());
}
}
어떻게하면 렌더링의 깜박임을 방지 할 수 있습니까? 깜박일 때 깜박임을 제외하고는 모두 잘 작동합니다. VelX 또는 VelY가 0이 아닌지 확인하기 위해 if 문을 추가 할 수 있다고 가정합니다. 그러나 사각형을 옮길 때 깜박입니다. 제발 절 끌어주세요.Java 2D 그래픽에서 깜박임을 방지하려면 어떻게합니까?
가벼운 구성 요소에 페인팅하여 'paintComponent' 메서드를 재정의하는 것이 좋습니다. [this] (http://www.oracle.com/technetwork/java/painting-140037.html) 및 [this] (https://docs.oracle.com/javase/tutorial/uiswing/painting/) – copeg