I'd like to make something similar to a cursor, ( I get no errors )
So basically I get the coordinates once I enter the applet, and based on them I have my image drawn.
Here's the code... Can you please tell me where I'm wrong ? Thanks
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Z_applets extends Applet implements
KeyListener, MouseListener, MouseMotionListener {
int z = 100;
int t = 100;
// boolean gigel = true;
//----------------- Images
Image image;
//-----------------
//----------------- Mouse Coordinates
Point p = null;
int x;
int y;
//----------------------------------
Color color = Color.GREEN;
public void init() {
addKeyListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
setBackground(Color.BLACK);
g.setColor(color);
g.drawImage(image, x, y, this);
g.fillOval(z, t, 15, 15);
}
public void update(Graphics g) {
paint(g);
}
public void loadImage() {
//URL url = getClass().getResource("borat.jpg");
//image = getToolkit().getImage(url);
try {
URL url = new URL(getCodeBase(), "trollface.png");
System.out.println(getCodeBase());
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("error" + e.getMessage());
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
char option;
option = ke.getKeyChar();
switch (option) {
case 'w': {
t--;
repaint();
break;
}
case 's': {
t++;
repaint();
break;
}
case 'a': {
z--;
repaint();
break;
}
case 'd': {
z++;
repaint();
break;
}
case '1': {
color = Color.GREEN;
break;
}
case '2': {
color = Color.RED;
break;
}
case '3': {
color = Color.YELLOW;
break;
}
// case 'r':
// {
// loadImage();
// repaint();
// break;
// }
}
}
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void mouseClicked(MouseEvent me) {
// p = me.getPoint();
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
// p=me.getPoint();
//-------Debug--------
System.out.println(p);
System.out.println(p.x);
System.out.println(p.y);
//----------------------
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent me) {
p = me.getPoint();
x = p.x;
y = p.y;
repaint();
}
}
Without knowing what problem you have exactly, I suppose the image isn't being moved.
I looks you don't register a MouseMotionListener so do that and implement the mouseMoved method.
Related
I have code which will draw circles depending on where the user clicks, and then will draw lines connecting those circles. I want to have the color of the circles and lines be set as Black by default, but the user can type either r,b,g,l (red, blue,green,black) to set the color of the NEXT circle and lines being drawn. What would I have to put inside of my KeyTyped method? I have if/else statements set up for whenever the user enters r,b,g, or l.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Circle extends JPanel implements MouseListener, KeyListener, MouseMotionListener {
private List<Point> points;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Circle().buildAndDisplayGui());
}
public Circle() {
points = new ArrayList<>();
setPreferredSize(new Dimension(500, 500));
setBackground(Color.white);
addMouseListener(this);
}
private void buildAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
int count = points.size();
for (int i = 0; i < count; i++) {
Point pt0 = points.get(i);
g.fillOval(pt0.x - 10, pt0.y - 11, 20, 20);
if (i > 0) {
Point pt1 = points.get(i - 1);
g.drawLine(pt1.x, pt1.y, pt0.x, pt0.y);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
//Prints the coordinates of the clicks
System.out.println("X: " + e.getX() + " Y: " + e.getY());
Point pt = new Point(e.getX(), e.getY());
points.add(pt);
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseExited(MouseEvent e) {
// Do nothing.
}
#Override
public void mousePressed(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseReleased(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'r') {
//Sets the color of the next circle and lines to red
} else {
if (e.getKeyChar() == 'b') {
//Sets the color of the next circle and lines to blue
} else {
if (e.getKeyChar() == 'g') {
//Sets the color of the next circle and lines to green
} else {
if (e.getKeyChar() == 'l') {
//Sets the color of the next circle and lines to black
}
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Current output:
Desired Output (If the user presses “r” after two mouse clicks and the does two more mouse clicks):
Add a Color instance variable to class Circle. In the example, I called it "currentColor". I set it to Color.black in the constructor.
Save a Color with each item in points. One way to do that is to have a parallel array. I don't like tightly coupled arrays, so I created a helper class in my example.
class PointAndColor {
Point thePoint;
Color theColor;
PointAndColor () {
theColor = Color.black;
thePoint = new Point (0,0);
}
PointAndColor (Point point, Color color) {
theColor = color;
thePoint = point;
}
Color getColor () { return theColor; }
Point getPoint () { return thePoint; }
}
I changed the generic type of the List of Points:
private List<PointAndColor> points;
private Color currentColor;
Example of saving the color with the point:
#Override
public void mouseClicked(MouseEvent e) {
//Prints the coordinates of the clicks
System.out.println("X: " + e.getX() + " Y: " + e.getY());
Point pt = new Point(e.getX(), e.getY());
points.add (new PointAndColor (pt, currentColor));
repaint();
}
Set the current color in the keyTyped method
#Override
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case 'r':
currentColor = Color.red;
break;
case 'g':
currentColor = Color.green;
break;
case 'b':
currentColor = Color.blue;
break;
case 'l':
currentColor = Color.black;
break;
default:
break;
}
System.out.println ("Color set to " + currentColor);
}
Retrieve the Color with the Point:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int count = points.size();
for (int i = 0; i < count; i++) {
Point pt0 = points.get(i).getPoint();
g.setColor (points.get(i).getColor());
g.fillOval(pt0.x - 10, pt0.y - 11, 20, 20);
if (i > 0) {
Point pt1 = points.get(i - 1).getPoint();
g.drawLine(pt1.x, pt1.y, pt0.x, pt0.y);
}
}
}
I am currently working on a 2D game which will be a puzzle. I got everything set up, got all my pieces added to my board (called View) and they're all aligned properly.
My next step is to select a piece by MouseEvent#mousePressed to be able to move it with the arrow keys with KeyEvent#keyPressed. The issue I'm currently running into is that my pieces will repaint themself whenever I move or resize the window. If I click on one piece and want to move it, the other pieces move too (in a way, they should not since one step equals about 100 pixel).
If anyone could tell me where my issue is and give me some advice, I would appreciate it.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Puzzle {
public static void main(String[] args) {
SwingUtilities.invokeLater(Puzzle::new);
}
public Puzzle() {
JFrame frame = new JFrame("Puzzle");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
View view = new View();
view.createPieces();
frame.setContentPane(view);
view.setFocusable(true);
MouseAdapterMod listener = new MouseAdapterMod(view);
view.addMouseListener(listener);
view.addKeyListener(listener);
frame.setVisible(true);
}
}
class View extends JPanel {
final List<Piece> pieces = new ArrayList<>();
public View() {
}
void createPieces() {
Piece topLeft = new Piece(100, 100, 0, Color.YELLOW);
pieces.add(topLeft);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gc = (Graphics2D) g;
for (Piece needle : pieces) {
needle.translate(needle.getLocation().x, needle.getLocation().y);
gc.setColor(needle.color);
gc.fill(needle);
gc.draw(needle);
}
}
}
class Piece extends Polygon {
int x;
int y;
final Color color;
Point location;
Piece(int x, int y, int type, Color color) {
this.x = x;
this.y = y;
this.color = color;
this.location = new Point(x, y);
int[] arrX = new int[] { 0, 100, 100, -100, -100, 0 };;
int[] arrY = new int[] { 0, 0, -100, -100, 100, 100 };
for (int drawIndex = 0; drawIndex < arrX.length; drawIndex++) {
addPoint(arrX[drawIndex], arrY[drawIndex]);
}
}
Point getLocation() {
return location;
}
void setLocation(Point location) {
this.location = location;
}
}
class MouseAdapterMod implements MouseListener, KeyListener {
final View view;
Polygon current;
public MouseAdapterMod(View view) {
this.view = view;
}
#Override
public void mousePressed(MouseEvent e) {
for (Piece piece : view.pieces) {
if (piece.contains(e.getX(), e.getY())) {
current = piece;
System.out.println(current);
}
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
current.translate(0, -100);
view.repaint();
break;
case KeyEvent.VK_DOWN:
current.translate(0, +100);
view.repaint();
break;
case KeyEvent.VK_LEFT:
current.translate(-100, 0);
view.repaint();
break;
case KeyEvent.VK_RIGHT:
current.translate(+100, 0);
view.repaint();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
(Sorry for the indent, stackoverflow is messing it up)
EDIT: But the problem is, eventually I want to move my pieces using Piece#setLocation to always keep track of their current x/y coordinates. I figured, I need to invoke Piece#getLocation in my painting to draw them based on the location but yet I do not know how. Using Piece#setLocation literally does nothing.
If you revert back to your Piece code from this question, you can move pieces by:
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
view.translatePiece(0, -100);
break;
case KeyEvent.VK_DOWN:
view.translatePiece(0, +100);
break;
case KeyEvent.VK_LEFT:
view.translatePiece(-100, 0);
break;
case KeyEvent.VK_RIGHT:
view.translatePiece(+100, 0);
break;
}
}
And adding to your view:
void translatePiece(int dx, int dy) {
if (current != null) {
current.x += dx;
current.y += dy;
repaint();
}
}
The if (current != null) { ... } test will prevent your application from crashing if you press an arrow key before clicking on a piece, which it currently does.
You could, instead of translating the Polygon, translate the location, and use it for painting:
In keyPressed, replace current.translate to translate the location instead of the whole Polygon (you could override Piece#translate to call current.getLocation().translate for example).
In View#paintComponent, replace:
needle.translate(needle.getLocation().x, needle.getLocation().y);
with
gc.translate(needle.getLocation().x, needle.getLocation().y);
and add
gc.translate(-needle.getLocation().x, -needle.getLocation().y);
at the end of your for-loop.
This will translate the whole Graphics2D to paint a polygon, and revert it after.
I made a ping pong game in Java but the paddles doesn't work, and I can't figure out the problem.
Main class: in the main class I give the thread and run the program:
package pingpong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class PingPong extends JFrame {
int Gwidth=400,Gheight=300;
Dimension screenSize = new Dimension(Gwidth,Gheight);
//double Buffering
Image dbImage;
Graphics dbg;
//ball objects
static Ball b = new Ball(193,143);
//constructor
public PingPong() {
this.setTitle("ping pong Game");
this.setResizable(false);
this.setSize(screenSize);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBackground(Color.black);
this.setVisible(true);
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
draw(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics g) {
b.draw(g);
b.p1.draw(g);
b.p2.draw(g);
g.setColor(Color.white);
g.drawString(""+b.p1Score,15,50);
g.drawString(""+b.p2Score,370,50);
repaint();
}
//event listining class
public class AL extends KeyAdapter { //key buildings
#Override
public void keyPressed(KeyEvent e) {
b.p1.keyPressed( e);
b.p2.keyPressed( e);
}
public void keyRealesed(KeyEvent e){
b.p1.keyReleased( e);
b.p2.keyReleased( e);
}
}
public static void main(String[] args) {
PingPong pp = new PingPong();
//create and start threads
Thread ball=new Thread(b);
ball.start();
Thread p1=new Thread(b.p1);
Thread p2= new Thread(b.p2);
p1.start();
p2.start();
}
}
this is my ball class:
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
public class Ball implements Runnable{
//global variables
int x,y,XDir,YDir;
//score
int p1Score,p2Score;
Paddle p1=new Paddle(15 , 140, 1);
Paddle p2=new Paddle(370, 140 ,2 );
Rectangle ball;
public Ball(int x,int y){
p1Score=p2Score=0;
this.x=x;
this.y=y;
//randomly moving the ball
Random r=new Random();
int rDir = r.nextInt(1);
if (rDir == 0) {
rDir--;
}setXDir(rDir);
int yrDir = r.nextInt(1);
if (yrDir == 0) {
yrDir--;
}setYDir(yrDir);
//create 'ball'
ball = new Rectangle(this.x, this.y,7, 7);
}
public void collision(){
if(ball.intersects(p1.paddle)){
setXDir(+1);}
if(ball.intersects(p2.paddle)){
setXDir(-1);}
}
public void draw(Graphics g){
g.setColor(Color.cyan);
g.fillRect(ball.x,ball.y,ball.width,ball.height);
}
public void move(){
collision();
ball.x +=XDir;
ball.y +=YDir;
//bounce the ball when edge is detected
if(ball.x<0){
setXDir(+1);
//add to score
p1Score++; //?
}
if(ball.x>=385){
setXDir(-1);
//add to score
p2Score++; //?
}
if(ball.y<=15)
setYDir(+1);
if(ball.y>=270)
setYDir(-1);
}
public void setXDir(int xdir){
XDir=xdir;
}
public void setYDir(int ydir){
YDir=ydir;
}
public void run(){
try{
while(true){
move();
Thread.sleep(4);
}
}catch(Exception e) {System.out.println("sorry"+e.getMessage());}
}
}
and there is my paddle class :
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Paddle implements Runnable {
int x, y, yDir, id;
Rectangle paddle;
public Paddle(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
paddle = new Rectangle(x, y, 15, 50);
}
public void keyPressed(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(+1);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(+1);
}
break;
}
}
public void keyReleased(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(0);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(0);
}
break;
}
}
public void draw(Graphics g) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 2:
g.setColor(Color.YELLOW);
//draw paddle #1
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
case 1:
g.setColor(Color.white);
// draw paddle #2
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
}
}
public void setYDir(int ydir) {
yDir = ydir;
}
public void move() {
paddle.x += yDir;
if (paddle.y <= 15) {
paddle.y = 15;
}
if (paddle.y >= 250) {
paddle.y = 250;
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(6);
}
} catch (Exception e) {
System.out.println("try again" + e.getMessage());
}
}
}
I personally think I have a problem in the paddle but I can't figure it out.
If you're moving your paddle in Y axis (inside move, this looks wrong:
paddle.x += yDir;
Should be
paddle.y += yDir;
I'm trying to make a game in Eclipse that runs on Windows 8 using type keys.
Whenever I run the app using extends Applet I just get a blank screen. I can change the color of the background but none of my images are showing. I can even play with the app and use my arrow keys to get the returns but I can't see anything on the screen. I'm not sure if I should extend Applet or JApplet.
Here's my code
package kiloboltgame;
import java.applet.Applet;
import java.awt.*;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Graphics;
import java.net.URL;
public class StartingClass extends Applet implements Runnable, KeyListener {
private Robot robot;
private Image image, currentSprite, character, characterDown, characterJumped, background;
private Graphics second;
private URL base;
private static Background bg1, bg2;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e){
//TODO: handle exception
}
character = getImage(base, "data/character.png");
characterDown = getImage(base, "data/down.png");
characterJumped = getImage(base, "data/jumped.png");
currentSprite = character;
background = getImage(base, "data/background.png");
}
#Override
public void start() {
bg1 = new Background(0,0);
bg2 = new Background(2160, 0);
robot = new Robot();
Thread thread = new Thread(this);
thread.start();
}
#Override
public void stop() {
//super.stop();
}
#Override
public void destroy() {
//super.destroy();
}
#Override
public void run() {
while (true) {
robot.update();
if (robot.isJumped()){
currentSprite = characterJumped;
} else if (robot.isJumped() == false && robot.isDucked() == false){
currentSprite = character;
}
bg1.update();
bg2.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void update(Graphics g){
if (image == null){
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g){
g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
g.drawImage(currentSprite, robot.getCenterX()-61, robot.getCenterY()-63, this);
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move Up");
break;
case KeyEvent.VK_DOWN:
currentSprite = characterDown;
if (robot.isJumped() == false){
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
robot.jump();
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;
case KeyEvent.VK_DOWN:
currentSprite = character;
break;
case KeyEvent.VK_LEFT:
robot.stopLeft();
break;
case KeyEvent.VK_RIGHT:
robot.stopRight();
break;
case KeyEvent.VK_SPACE:
//System.out.println("Stop jumping");
break;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public static Background getBg1(){
return bg1;
}
public static Background getBg2(){
return bg2;
}
}
I was trying to modify an existing code to rotate an image based on key presses. so far i've managed to do the following and I'm stuck. i've made use of Affine transform for the first time. The image rotates only once when it's supposed to rotate as many times as the RIGHT key is pressed.
package aircraftPackage;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class RotateImage extends JFrame implements KeyListener {
private static final long serialVersionUID = 1L;
private Image TestImage;
private BufferedImage bf;
private int cordX = 100;
private int cordY = 100;
private double currentAngle;
public RotateImage(Image TestImage) {
this.TestImage = TestImage;
MediaTracker mt = new MediaTracker(this);
mt.addImage(TestImage, 0);
try {
mt.waitForID(0);
}
catch (Exception e) {
e.printStackTrace();
}
setTitle("Testing....");
setSize(500, 500);
imageLoader();
setVisible(true);
}
public void rotate() {
//rotate 5 degrees at a time
currentAngle+=5.0;
if (currentAngle >= 360.0) {
currentAngle = 0;
}
repaint();
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB);
try{
animation(bf.getGraphics());
g.drawImage(bf,0,0,null);
}catch(Exception ex){
}
}
public void animation(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
AffineTransform origXform = g2d.getTransform();
AffineTransform newXform = (AffineTransform)(origXform.clone());
//center of rotation is center of the panel
int xRot = this.getWidth()/2;
int yRot = this.getHeight()/2;
newXform.rotate(Math.toRadians(currentAngle), xRot, yRot);
g2d.setTransform(newXform);
//draw image centered in panel
int x = (getWidth() - TestImage.getWidth(this))/2;
int y = (getHeight() - TestImage.getHeight(this))/2;
g2d.drawImage(TestImage, x, y, this);
g2d.setTransform(origXform);
g.drawImage(TestImage, cordX, cordY, this);
}
public static void main(String[] args) {
new RotateImage(null);
}
public void keyPressed(KeyEvent ke) {
final RotateImage ri = new RotateImage(TestImage);
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX += 5;
ri.rotate();
}
break;
case KeyEvent.VK_LEFT: {
cordX -= 5;
}
break;
case KeyEvent.VK_DOWN: {
cordY += 5;
}
break;
case KeyEvent.VK_UP: {
cordY -= 3;
}
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
}
would be helpful if anyone could correct me on where im making the mistake.
Thanks
the problem you are creating new rotate image on each event key so it looks like not working
try to change the place of this line to be none modifiable on each key event
public static void main(String[] args) {
new RotateImage(null);
}
public void keyPressed(KeyEvent ke) {
final RotateImage ri = new RotateImage(TestImage);
UPDATE:
the reason is because the value of constructor is null you should pass image
new RotateImage(null);
modify this on your code
1)make it static
private static Image TestImage;
2)define
private static RotateImage ri;
3)call in main like this
public static void main(String[] args) {
ri = new RotateImage(TestImage);
}
step 4(removed)
UPDATE:
read these question on stack overflow
another question
UPDATE2:
here is the full code it works perfectly ( the right key ) dont foget to include you image in the same package and its the same type .png here is the code
package aircraftPackage;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class RotateImage extends JFrame implements KeyListener {
private static final long serialVersionUID = 1L;
private static Image TestImage;
private static RotateImage ri;
private BufferedImage bf;
private int cordX = 100;
private int cordY = 100;
private double currentAngle;
public RotateImage(Image TestImage) {
this.TestImage = TestImage;
MediaTracker mt = new MediaTracker(this);
mt.addImage(TestImage, 0);
try {
mt.waitForID(0);
}
catch (Exception e) {
e.printStackTrace();
}
setTitle("Testing....");
setSize(500, 500);
imageLoader();
setVisible(true);
}
public void rotate() {
//rotate 5 degrees at a time
currentAngle+=5.0;
if (currentAngle >= 360.0) {
currentAngle = 0;
}
repaint();
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB);
try{
animation(bf.getGraphics());
g.drawImage(bf,0,0,null);
}catch(Exception ex){
}
}
public void animation(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
AffineTransform origXform = g2d.getTransform();
AffineTransform newXform = (AffineTransform)(origXform.clone());
//center of rotation is center of the panel
int xRot = this.getWidth()/2;
int yRot = this.getHeight()/2;
newXform.rotate(Math.toRadians(currentAngle), xRot, yRot);
g2d.setTransform(newXform);
//draw image centered in panel
int x = (getWidth() - TestImage.getWidth(this))/2;
int y = (getHeight() - TestImage.getHeight(this))/2;
g2d.drawImage(TestImage, x, y, this);
g2d.setTransform(origXform);
g.drawImage(TestImage, cordX, cordY, this);
}
public static void main(String[] args) {
ri = new RotateImage(TestImage);
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX += 5;
ri.rotate();
}
break;
case KeyEvent.VK_LEFT: {
cordX -= 5;
ri.rotate();
}
break;
case KeyEvent.VK_DOWN: {
cordY += 5;
ri.rotate();
}
break;
case KeyEvent.VK_UP: {
cordY -= 3;
ri.rotate();
}
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
}
public void keyPressed(KeyEvent ke) {
final RotateImage ri = new RotateImage(TestImage);
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX += 5;
ri.rotate();
}
It seems that you are rotating the same image every time so it will always rotate for only 5 deg.
edit : hum too late . . see shareef post.