Hello there, My name is, as you might have guessed, Matthias. I just today(!) bought ‘Beginning Java Se 6 Game Programming’ Third Edition by Jonathan S. Harbour. I used an example in the book to rotate a polygon when pressing the left key or right key or clicking the left or right mouse button. Now it did sort of work but there was alot of flickering so I tried to implement a backbuffer since the book had covered that briefly earlier. However my attempts were futile and I am now sort of stuck. There is no hurry in this, I am doing this as a hobby. Please realize that altough I have a intuition for programming, when it comes to Java I am a beginner. Any help is very much appreciated. Here is my source code:
package randomshapes;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class RandomShapes extends Applet implements KeyListener, MouseListener{
private int[]xpoints = {0,-10,-7,7,10};
private int[]ypoints = {-10,-2,10,10,-2};
private Polygon poly;
BufferedImage backbuffer;
Graphics2D g2d;
int rotation = 0;
//applet init
public void init(){
poly = new Polygon(xpoints,ypoints,xpoints.length);
addKeyListener(this);
addMouseListener(this);
backbuffer = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
}
public void update(Graphics g){
Graphics2D g2d = (Graphics2D) g;
//AffineTransform identity = new AffineTransform();
int width = getSize().width;
int height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
g2d.translate(width/2, height/2);
g2d.scale(20, 20);
g2d.rotate(Math.toRadians(rotation));
g2d.setColor(Color.RED);
g2d.fill(poly);
g2d.drawImage(backbuffer, 0, 0,this);
paint(g2d);
}
public void paint(Graphics g) {
g.drawImage(backbuffer, 0, 0,this);
}
public void keyReleased(KeyEvent k){}
public void keyTyped(KeyEvent k){}
public void keyPressed(KeyEvent k){
switch (k.getKeyCode()){
case KeyEvent.VK_LEFT:
rotation--;
if (rotation < 0) rotation = 359;
//repaint();
update(g2d);
break;
case KeyEvent.VK_RIGHT:
rotation++;
if (rotation > 360) rotation = 0;
//repaint();
update(g2d);
break;
}
}
public void mouseEntered(MouseEvent m) {}
public void mouseExited(MouseEvent m) {}
public void mouseReleased(MouseEvent m) {}
public void mouseClicked(MouseEvent m) {}
public void mousePressed(MouseEvent m) {
switch(m.getButton()){
case MouseEvent.BUTTON1:
rotation--;
if (rotation < 0) rotation = 359;
//repaint();
update(g2d);
break;
case MouseEvent.BUTTON3:
rotation++;
if (rotation > 360) rotation = 0;
//repaint();
update(g2d);
break;
}
}
}