Zastosowałem rozwiązanie z książki java Tworzenie gier. Mianowicie do klasy MyFrame dopisałem dwie metody:
Kopiuj
package pl.danek.grafika;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class MyFrame extends JFrame{
private GraphicsDevice device;
public MyFrame(){
setUndecorated(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = environment.getDefaultScreenDevice();
getRootPane().setDoubleBuffered(true);
}
public void update() {
Window window = device.getFullScreenWindow();
if (window != null) {
BufferStrategy strategy = window.getBufferStrategy();
if (!strategy.contentsLost()) {
strategy.show();
}
}
Toolkit.getDefaultToolkit().sync();
}
@Override
public Graphics getGraphics() {
try {
Window window = device.getFullScreenWindow();
if (window != null) {
BufferStrategy strategy = window.getBufferStrategy();
return (Graphics2D) strategy.getDrawGraphics();
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
}
Pochodza one z ksiażki.
Rysowanie realizuje tak(Klasa Manager, wyciąłem to co nie istotne):
Kopiuj
private void draw(Graphics g){
g.setColor(Color.white);
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
g.setColor(Color.red);
g.fillRect(x, y,20, 20);
g.drawString("Speed"+speed, 10, 10);
}
private void gameLoop(){
do {
checkInput();
Graphics g = frame.getGraphics();
draw(g);
g.dispose();
frame.update();
} while (frame.isVisible());
}
Jest to po częsci z tej książki. Działa tak jak powinno, nie ma tego efetku "szarpania" Dzieki wielkie za pomoc ;)