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.
Related
I'm trying to make a racing game with the top down view on a static player in the middle of the screen, so instead of moving the player through the map, the map would move around the player. Since it's a racing game, I wanted it to also be somewhat similar to a car, but I've been having trouble with rotating the map around the player and having that work with translations.
I've tried keeping track of the center by adding or subtracting from it, which is what I did for the translations, but it doesn't work with the rotate method. The rotate function wouldn't rotate about the player and instead would rotate the player around some other point, and the translations would snap to a different location from the rotations. I'm sure my approach is flawed, and I have read about layers and such, but I'm not sure what I can do with them or how to use them. Also, any recommendations as to how to use java graphics in general would be greatly appreciated!
This is what I have in my main:
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class game
{
public static void main(String []args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 600;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Map b = new Map();
frame.add(b,BorderLayout.CENTER);
frame.setVisible(true);
b.startAnimation();
}
}
And this is the class that handles all the graphics
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Map extends JComponent implements Runnable, KeyListener
{
private int speed = 5;
private int xcenter = 500; // starts on player
private int ycenter = 300;
private double angle = 0.0;
private int[] xcords = {xcenter+10, xcenter, xcenter+20};
private int[] ycords = {ycenter-10, ycenter+20, ycenter+20};
private boolean moveNorth = false;
private boolean moveEast = false;
private boolean moveSouth = false;
private boolean moveWest = false;
public Map()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void startAnimation()
{
Thread t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g)
{
g.fillPolygon(xcords, ycords, 3);
// move screen
if(moveNorth)
{
ycenter += speed;
g.translate(xcenter, ycenter);
}
else if(moveEast)
{
angle += ((1 * Math.PI/180) % (2 * Math.PI));
((Graphics2D) g).rotate(angle, 0, 0);
}
else if(moveSouth)
{
System.out.println(xcenter + ", " + ycenter);
ycenter -= speed;
((Graphics2D) g).rotate(angle, 0, 0);
g.translate(xcenter, ycenter);
}
else if(moveWest)
{
angle -= Math.toRadians(1) % (2 * Math.PI);
((Graphics2D) g).rotate(angle, 0, 0);
}
for(int i = -10; i < 21; i++)
{
g.drawLine(i * 50, -1000, i * 50, 1000);
g.drawLine(-1000, i * 50, 1000, i * 50);
}
g.drawOval(0, 0, 35, 35);
}
public void run()
{
while (true)
{
try
{
if(moveNorth || moveEast || moveSouth || moveWest)
{
repaint();
}
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
}
}
public void keyPressed(KeyEvent e)
{
if(e.getExtendedKeyCode() == 68) // d
{
moveEast = true;
}
else if(e.getExtendedKeyCode() == 87) // w
{
moveNorth = true;
}
else if(e.getExtendedKeyCode() == 65) // a
{
moveWest = true;
}
else if(e.getExtendedKeyCode() == 83) // s
{
moveSouth = true;
}
}
public void keyReleased(KeyEvent e)
{
moveNorth = false;
moveEast = false;
moveSouth = false;
moveWest = false;
}
public void keyTyped(KeyEvent e)
{
}
}
You have to keep in mind that transformations are compounding, so if you rotate the Graphics context by 45 degrees, everything painted after it will be rotated 45 degrees (around the point of rotation), if you rotate it again by 45 degrees, everything painted after it will be rotated a total of 90 degrees.
If you want to paint additional content after a transformation, then you either need to undo the transformation, or, preferably, take a snapshot of the Graphics context and dispose of it (the snapshot) when you're done.
You also need to beware of the point of rotation, Graphics2D#rotate(double) will rotate the Graphics around the point of origin (ie 0x0), which may not be desirable. You can change this by either changing the origin point (ie translate) or using Graphics2D#rotate(double, double, double), which allows you to define the point of rotation.
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
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.image.BufferedImage;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class TestPane extends JPanel {
enum Direction {
LEFT, RIGHT;
}
protected enum InputAction {
PRESSED_LEFT, PRESSED_RIGHT, RELEASED_LEFT, RELEASED_RIGHT
}
private BufferedImage car;
private BufferedImage road;
private Set<Direction> directions = new TreeSet<>();
private double directionOfRotation = 0;
public TestPane() throws IOException {
car = ImageIO.read(getClass().getResource("/images/Car.png"));
road = ImageIO.read(getClass().getResource("/images/Road.png"));
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), InputAction.PRESSED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), InputAction.RELEASED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), InputAction.PRESSED_RIGHT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), InputAction.RELEASED_RIGHT);
am.put(InputAction.PRESSED_LEFT, new DirectionAction(Direction.LEFT, true));
am.put(InputAction.RELEASED_LEFT, new DirectionAction(Direction.LEFT, false));
am.put(InputAction.PRESSED_RIGHT, new DirectionAction(Direction.RIGHT, true));
am.put(InputAction.RELEASED_RIGHT, new DirectionAction(Direction.RIGHT, false));
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (directions.contains(Direction.RIGHT)) {
directionOfRotation += 1;
} else if (directions.contains(Direction.LEFT)) {
directionOfRotation -= 1;
}
// No doughnuts for you :P
if (directionOfRotation > 180) {
directionOfRotation = 180;
} else if (directionOfRotation < -180) {
directionOfRotation = -180;
}
repaint();
}
});
timer.start();
}
protected void setDirectionActive(Direction direction, boolean active) {
if (active) {
directions.add(direction);
} else {
directions.remove(direction);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(213, 216);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
drawRoadSurface(g2d);
drawCar(g2d);
g2d.dispose();
}
protected void drawCar(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
int x = (getWidth() - car.getWidth()) / 2;
int y = (getHeight() - car.getHeight()) / 2;
g2d.drawImage(car, x, y, this);
g2d.dispose();
}
protected void drawRoadSurface(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
// This sets the point of rotation at the center of the window
int midX = getWidth() / 2;
int midY = getHeight() / 2;
g2d.rotate(Math.toRadians(directionOfRotation), midX, midY);
// We then need to offset the top/left corner so that what
// we want draw appears to be in the center of the window,
// and thus will be rotated around it's center
int x = midX - (road.getWidth() / 2);
int y = midY - (road.getHeight() / 2);
g2d.drawImage(road, x, y, this);
g2d.dispose();
}
protected class DirectionAction extends AbstractAction {
private Direction direction;
private boolean active;
public DirectionAction(Direction direction, boolean active) {
this.direction = direction;
this.active = active;
}
#Override
public void actionPerformed(ActionEvent e) {
setDirectionActive(direction, active);
}
}
}
}
I want it so when my player goes off the platform, (in checkCollision() method PlatformerPanel class) it will fall and then do something when gone off the screen, i haven't set up an end game screen yet but that's what I'm planning to do. Anyway, the problem is that it goes way too fast for some reason and falls too early, and also when an arrow key is pressed while its falling it will go back up to the platform.
Please try to help me overcome this or think of a new, easy to understand, way to do this/make this work the way i am planning.
EDIT 1:
I fixed the thing where it falls too early so don't worry about that
```
public class PlatformerMain {
public static void main(String[] args) {
PlatformerGameFrame platformerGame = new PlatformerGameFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGameFrame extends JFrame{
PlatformerGamePanel panel;
PlatformerGameFrame() {
panel = new PlatformerGamePanel();
this.add(panel);
this.setTitle("Platformer Game");
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(new Color(0,0,0));
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGamePanel extends JPanel implements Runnable{
PlatformerPlayer player1;
PlatformerMap map1;
static final int SCREEN_WIDTH = 1000;
static final int SCREEN_HEIGHT = 600;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 60;
static final Dimension SCREEN_SIZE = new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT);
static boolean falling = false;
Image backgroundImage;
Thread gameThread;
Image image;
Graphics graphics;
PlatformerMap map;
public PlatformerGamePanel() {
java.net.URL imgIcon = Main.class.getResource(
"/Resources/spaceImage.jpg");
backgroundImage = new ImageIcon(imgIcon).getImage();
newPlayer();
newMap();
this.setFocusable(true);
this.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
player1.KeyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
player1.KeyReleased(e);
}
});
this.setPreferredSize(SCREEN_SIZE);
this.setOpaque(true);
gameThread = new Thread(this);
gameThread.start();
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
draw(graphics);
g.drawImage(image, 0,0, null);
}
public void draw(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(backgroundImage, 0,0, null);
player1.paint(g);
map.paint(g);
}
public void newPlayer() {
player1 = new PlatformerPlayer((SCREEN_WIDTH/2)-(PLAYER_WIDTH/2), (SCREEN_HEIGHT/2)-(PLAYER_WIDTH/2), PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void newMap() {
map = new PlatformerMap();
}
public void checkCollision() {
if(player1.x > SCREEN_WIDTH-PLAYER_WIDTH) {
player1.x = SCREEN_WIDTH-PLAYER_WIDTH;
}
else if(player1.x < 0) {
player1.x = 0;
}
if(!(player1.x >map.PLATFORM_WIDTH)) {
if(player1.y > SCREEN_HEIGHT-250) {
player1.y = SCREEN_HEIGHT-250;
}
} else if(player1.x > map.PLATFORM_WIDTH) {
gravity();
}
}
public void falling() {
}
public void gravity() {
player1.gravity();
}
public void move() {
player1.move();
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 120.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1) {
move();
checkCollision();
gravity();
repaint();
delta--;
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerPlayer extends Rectangle {
/*static int playerPosX = 100;
static int playerPosY = 100;*/
static double velocityY = 0;
static double velocityX = 0;
static int vertical_position;
static final int TERMINAL_VELOCITY = 200;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 50;
static int speed = 2;
protected boolean falling = true;
protected boolean jumping = false;
double gravity = 0.05;
public PlatformerPlayer(int x, int y, int PLAYERWIDTH, int PLAYERHEIGHT) {
super(x,y,PLAYERWIDTH,PLAYERHEIGHT);
}
public void KeyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(-speed);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(speed);
move();
}
}
public void KeyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(0);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(0);
move();
}
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.red);
g2D.fillRect(x, y, PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void setYDirection(int YDirection) {
velocityY = YDirection;
}
public void setXDirection(int XDirection) {
if(speed > 10) {
speed = 10;
}
velocityX = XDirection;
}
public void move() {
y += velocityY;
x += velocityX;
}
public void gravity() {
velocityY += gravity;
if (velocityY > TERMINAL_VELOCITY)
{
velocityY = TERMINAL_VELOCITY;
}
vertical_position -= velocityY;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerMap extends Rectangle {
int PLATFORM_WIDTH = 600;
int PLATFORM_HEIGHT = 150;
public PlatformerMap() {
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.gray);
g2D.fillRect(100,400,PLATFORM_WIDTH,PLATFORM_HEIGHT);
}
}
Writing this piece of code following a tutorial. I have no idea why the update and render methods are asking to cast to particle.get(i). I didn't think this would have to be done.
Is there something i am missing here? Guidance would be appreciated. (Marked areas of concern with "" "")
package particles;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import javax.swing.JFrame;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.Particle;
public class createparticles extends JFrame {
private ArrayList<Particle> particles = new ArrayList<Particle>(500);
private int x = 0;
private int y = 0;
private int size;
private int life;
private Color color;
private BufferStrategy bufferstrat = null;
private Canvas render;
public static void main(String [] args){
createparticles window = new createparticles(450, 280, "Particles");
window.pollInput();
window.loop();
}
public void pollInput() {
render.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited (MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
}
public createparticles (int width, int height, String title){
super();
setTitle(title);
setIgnoreRepaint(true);
setResizable(false);
render = new Canvas();
render.setIgnoreRepaint(true);
int nHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
int nWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
nHeight /=2;
nWidth /=2;
setBounds(nWidth-(width/2), nHeight-(height /2),width, height);
render.setBounds(nWidth-(width/2), nHeight-(height/2), nWidth, nHeight);
add(render);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
render.createBufferStrategy(2);
bufferstrat = render.getBufferStrategy();
}
public void loop() {
while(true){
update();
render();
try{
Thread.sleep(1000/60);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void update() {
Point p = render.getMousePosition();
if(p !=null){
x = p.x;
y = p.y;
}
**for(int i = 0; i <=particles.size() - 1; i++) {
if(particles.get(i).update())
particles.remove(i);**
}
}
public void render(Graphics g){
Graphics g2d = (Graphics2D) g.create();
g2d.setColor(color);
g2d.fillRect(x -(size/2), y - (size/2), size, size);
g2d.dispose();
do{
do{
bufferstrat.getDrawGraphics();
g2d.fillRect(0,0, render.getWidth(), render.getHeight());
renderParticles(g2d);
g2d.dispose();
} while(bufferstrat.contentsRestored());
bufferstrat.show();
}while(bufferstrat.contentsLost());
}
public void renderParticles(Graphics g2d){
**for(int i =0; i <= particles.size() - 1; i++){
particles.get(i).render(g2d);**
}
}
}
Pong.Java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Pong {
private static final int WIDTH = 900, HEIGHT = 700;
JFrame win = new JFrame();
Paddle paddleOne = new Paddle(1);
Paddle paddleTwo = new Paddle(2);
Graphics g;
Pong(){
init();
}
void init(){
win.setTitle("PONG");
win.setSize(WIDTH, HEIGHT);
win.addKeyListener(keyListener);
win.setLocationRelativeTo(null);
win.getContentPane().setBackground(Color.black);
win.setVisible(true);
win.getContentPane().validate();
win.repaint();
}
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());
System.out.println("drawn");
}
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key){
case 87:
System.out.println("Player 1 Up");
break;
case 83:
System.out.println("Player 1 Down");
break;
case 38:
System.out.println("Player 2 Up");
break;
case 40:
System.out.println("Player 2 Down");
break;
}
win.getContentPane().validate();
win.repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
};
public static void main(String[] args) {
Pong p = new Pong();
}
}
Paddle.Java
public class Paddle{
private int WIDTH = 50, HEIGHT = 150, X, Y;
int playerNum;
Paddle(int playerNum){
if(playerNum == 1){
X = 10;
Y = 10;
}else if (playerNum == 2){
X = 500;
Y = 10;
}
}
public void setX(int x){
X = x;
}
public void setY(int y){
Y = y;
}
public int getWIDTH() {
return WIDTH;
}
public int getHEIGHT() {
return HEIGHT;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
}
I'm relatively new to Java programming, or more specifically Awt & Swing, what my question is, why isn't my rectangle drawing? Any help is appreciated. Thank you so much!
In order for something to be painted within in Swing, it first must extend from something Swing know's how to paint, this commonly means a JComponent (or more typically a JPanel).
Then you can override one of the paint methods, which is called by the painting subsystem, in this case, it's generally preferred to override paintComponent, but don't forget to call super.paintComponent before you do any custom painting, or you're setting yourself up for some weird and generally unpredictable painting issues.
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Pongo {
public static void main(String[] args) {
new Pongo();
}
public Pongo() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PongPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PongPane extends JPanel {
private static final int WIDTH = 900, HEIGHT = 700;
Paddle paddleOne = new Paddle(1);
Paddle paddleTwo = new Paddle(2);
public PongPane() {
setBackground(Color.BLACK);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());
//System.out.println("drawn"); //Should not put something here which may overhead.
}
}
public class Paddle {
private int WIDTH = 50, HEIGHT = 150, X, Y;
int playerNum;
Paddle(int playerNum) {
if (playerNum == 1) {
X = 10;
Y = 10;
} else if (playerNum == 2) {
X = 500;
Y = 10;
}
}
public void setX(int x) {
X = x;
}
public void setY(int y) {
Y = y;
}
public int getWIDTH() {
return WIDTH;
}
public int getHEIGHT() {
return HEIGHT;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
}
}
I would also discourage the use of KeyListener within this context and inside advice the use of the key bindings API, it doesn't suffer from the same focus related issues that KeyListener does. See How to Use Key Bindings for more details
You need to overriding paintComponents to draw.
Here is your Pong.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Pong {
private static final int WIDTH = 900, HEIGHT = 700;
JFrame win = new JFrame();
Paddle paddleOne = new Paddle(1);
Paddle paddleTwo = new Paddle(2);
Graphics g;
Pong() {
init();
}
void init() {
win.setTitle("PONG");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setSize(WIDTH, HEIGHT);
win.addKeyListener(keyListener);
win.setLocationRelativeTo(null);
win.add(new Panel(paddleOne));
win.getContentPane().setBackground(Color.black);
win.setVisible(true);
win.getContentPane().validate();
win.repaint();
}
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case 87:
System.out.println("Player 1 Up");
break;
case 83:
System.out.println("Player 1 Down");
break;
case 38:
System.out.println("Player 2 Up");
break;
case 40:
System.out.println("Player 2 Down");
break;
}
win.getContentPane().validate();
win.repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Pong();
}
});
}
}
Here Panel.java in where paintComponent overridden.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panel extends JPanel{
private Paddle paddleOne;
public Panel(Paddle pdl) {
paddleOne = pdl;
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());
//System.out.println("drawn"); //Should not put something here which may overhead.
}
}
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.