how can i display my player's sprite sheet using java - java

hello i really need your help if you would be kind to help me out i'll appreciate it a lot .i have recently started learning java
i am making a java program that allows my player to jump and move to the place of the mouse i think that i have succeeded to make that but it not really SPECIFIC ;
also i want to display my sprite sheet so that he would look like he is really walking but i am having a problem in this part
here is my codes :
package animation;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.awt.*;
import javax.swing.*;
import animation.Boulle.move;
import gfx.Sprite;
import gfx.SpriteSheet;
public class deux_bulle extends JFrame implements MouseListener, MouseMotionListener {
Monp p;
int X, Y, x = 150, y = 150;
Thread t, t2, t3,t4;
int f = 0;
boolean b = false;
public Graphics g;
private int framedelay;
public static SpriteSheet sheet;
public static gfx.Sprite Sprite[] = new gfx.Sprite[3]; // my sprite sheet
// has 3 pictures
public deux_bulle() {
setSize(400, 400);
p = new Monp();
sheet = new SpriteSheet("/Untitled.png");
add(p);
p.addMouseListener(this);
p.addMouseMotionListener(this);
for (int i = 0; i < Sprite.length; i++) {
Sprite[i] = new Sprite(sheet, i + 1, 1);
}
}
class Monp extends JPanel {
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
}
}
class moveX implements Runnable {
#Override
public void run() {
while (x < X) {
try {
x++;
if (f < 3)
//g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (x > X) {
try {
x--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class image implements Runnable{
public void run() {
framedelay++;
if (framedelay>=3)
{f++;
if(f>=3)
{f=0;}
framedelay=0;}
}}
class moveY implements Runnable {
#Override
public void run() {
while (y < Y) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y > Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class jump implements Runnable {
#Override
public void run() {
int p = y;
while (y != Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y != p) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
deux_bulle db = new deux_bulle();
db.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Y = 70;
t3 = new Thread(new jump());
t3.start();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
X = e.getX();
Y = e.getY();
t4 = new Thread(new image());
t = new Thread(new moveX());
t2 = new Thread(new moveY());
t.start();
t2.start();
t4.start();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
my sprite sheet class
package gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(String path) {
try {
sheet= ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getSprite(int x,int y)
{
return sheet.getSubimage(x*66-66,y*66-66,66,66);}
}
my sprite class
package gfx;
import java.awt.image.BufferedImage;
public class Sprite {
public SpriteSheet sheet;
public BufferedImage image;
public Sprite(SpriteSheet sheet,int x,int y) {
image= sheet.getSprite(x, y);
}
public BufferedImage getBufferedIamge(){
return image;
}
}

Related

I made it so that the player is facing the mouse direction, but because of that there is a problem

So basically I wanted to create zombies to interact with them later on, but when I drew them I noticed that all of them are turning to the same direction as the player (to mouse) it happened with everything I drew. How do I fix that? (give each zombie it's own position independent from the mouse direction)
Screen.java
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
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.JPanel;
public class Screen extends JPanel implements KeyListener, MouseListener, MouseMotionListener {
private Enemy[] enemy;
private Bullet bullet;
private Player player;
boolean collisionBetweenBnZ = false;
private int mX, mY, key;
private List<Bullet> firedBullets = new ArrayList<Bullet>();
public Screen() {
player = new Player(400, 500);
enemy = new Enemy[10];
for (int i = 0; i < enemy.length; i++) {
enemy[i] = new Enemy();
}
setFocusable(true);
addKeyListener(this);
addMouseMotionListener(this);
addMouseListener(this);
this.requestFocusInWindow();
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
//an obstacle for zombies
g.fillRect(0, 400, 800, 4);
//drawing each bullet as soon as they are added to the list (when pressing mouse button)
for (int i = 0; i < firedBullets.size(); i++) {
firedBullets.get(i).drawBullet(g);
}
//drawing sprites
player.drawPlayer(g);
for (int i = 0; i < enemy.length; i++) {
enemy[i].drawEnemy(g);
}
}
public static int clamp(int num, int min, int max) { //method that prevents you from going beyond the window
if (num >= max) return num = max;
else if (num <= min) return num = min;
else return num;
}
public void fire() {
bullet = new Bullet(player.playerX(), player.playerY());
bullet.updateAngle(mX, mY, player.playerX(), player.playerY());
firedBullets.add(bullet);
}
public void animate() {
while (true) {
try {
Thread.sleep(10); //in milliseconds
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
player.tick();
/*for (int i = 0; i < )
enemy.tick();*/
//System.out.println("X: " + mX + "\n" + "Y: " + mY);
for (int i = 0; i < firedBullets.size(); i++) {
firedBullets.get(i).launch();
}
//if () getbounds
repaint();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
player.setVelX(-2);
}
else if (key == KeyEvent.VK_D) {
player.setVelX(2);
}
else if (key == KeyEvent.VK_S) {
player.setVelY(2);
}
else if (key == KeyEvent.VK_W) {
player.setVelY(-2);
}
else if (key == KeyEvent.VK_SPACE) {
//bullet.shootBullet = true;
}
else if (key == KeyEvent.VK_A && key == KeyEvent.VK_D) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_W && key == KeyEvent.VK_S) {
player.setVelY(0);
}
}
public void keyReleased(KeyEvent e) {
key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_D) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_S) {
player.setVelY(0);
}
else if (key == KeyEvent.VK_W) {
player.setVelY(0);
}
else if (key == KeyEvent.VK_SPACE) {
//bullet.shootBullet = false;
}
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
mX = e.getX();
mY = e.getY();
player.updateAngle(mX, mY);
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
fire();
}
#Override
public void mousePressed(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
}
}
Enemy.java
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.concurrent.ThreadLocalRandom;
public class Enemy {
private int health, width, height;
private int enemyX, enemyY, velY;
private BufferedImage img;
public Enemy() {
try {
img = ImageIO.read(new File("/Users/david/Desktop/Enemy_Sprite.png"));
} catch (IOException e) {
e.printStackTrace();
}
health = 100;
width = img.getWidth();
height = img.getHeight();
enemyX = ThreadLocalRandom.current().nextInt(50, 750);
enemyY = ThreadLocalRandom.current().nextInt(0, 200);
}
public Rectangle getBounds() {
return new Rectangle(enemyX, enemyY, width, height);
}
public void setVelY(int y) {
velY = y;
}
public void tick() {
enemyY += velY;
}
public boolean obstacleInteraction() {
//if (getBounds() == )
return true;
}
public void drawEnemy(Graphics g) {
g.drawImage(img, enemyX, enemyY, null);
}
}
I figured it out thanks to this person. So basically at the end of my code where I draw player and make him rotate to the mouse position put the saved original plane position
g.setTransform(oldAT);

Fix background image applet

I'm having some issues with my code.
I want to fix the background image to stay there fixed, meanwhile other components can move.
It's a simple a game where a circle avoid the squares but the istruction about the game will be added further.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;
import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{
Thread r;
Image bg = null;
int a,b;
int x = 600;
int y = 400;
public void init(){
setSize(600,600);
try
{
MediaTracker tr = new MediaTracker (this);
bg = getImage
(new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
tr.addImage(bg, 0);
} catch (Exception e) { System.out.println(e.toString());
}
}
public void start(){
if(r == null){
r = new Thread(this);
r.start();
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,this);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(20));
g2.draw(new Line2D.Float(0, 500, 600, 500));
g.fillRect(x, y, 20, 20);
}
public void pp(Graphics g){
}
public void run() {
Thread Th = Thread.currentThread();
while(r == Th) {
if(a < 600) {
a = a+10;
x = x-10;
repaint();
}else{
repaint();
a = 30;
x = 600;
}
try {
Thread.sleep(100);
} catch(InterruptedException e) { }
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
if you run the code, you'll see that the line and the background will be loaded a lot of time...

Move a Graphic in Java,using keyboard arrows and mouseEvent

I'm a beginner in learning this.Doing a test by drawing a triangle and now I want to move it.it's not working so I want to ask what's my mistake.Sorry it's long.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args)
{
Test t = new Test();
}
public Test()
{
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new JPanel();
add(tripanel);
triangle = new Triangle();
tripanel.addKeyListener(null);
tripanel.addMouseListener(null);
tripanel.addMouseMotionListener(null);
setVisible(true);
}
static class move extends JPanel implements KeyListener,MouseListener, MouseMotionListener{
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move()
{
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void keyPressed(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
System.out.println("key code is" +KeyCode);
/*switch (KeyCode)
{
case KeyEvent.VK_UP:
triangle.moveTriangle(-10, 0);
break;
case KeyEvent.VK_DOWN:
triangle.moveTriangle(10, 0);
break;
case KeyEvent.VK_LEFT:
triangle.moveTriangle(0, -10);
break;
case KeyEvent.VK_RIGHT:
triangle.moveTriangle(0, 10);
break;
}
repaint();*/
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if(e.isControlDown())
color = Color.RED;
else
color = Color.BLACK;
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getPoint());
}
}
public void paint(Graphics g)
{
super.paint(g);
triangle.drawTriangle(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
triangle.drawTriangle(g);
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle()
{
p1 = new Point(200,200);
p2 = new Point(170,230);
p3 = new Point(230,230);
}
public void moveTriangle(int dx, int dy)
{
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g)
{
g.drawLine(p1.getX(), p1.getY(),p2.getX(),p2.getY());
g.drawLine(p2.getX(),p2.getY(),p3.getX(),p3.getY());
g.drawLine(p3.getX(), p3.getY(),p1.getX(),p1.getY());
}
}
public class Point {
private int x;
private int y;
public Point(int X, int Y)
{
x = X;
y = Y;
}
public void setX(int X)
{
x = X;
}
public void setY(int Y)
{
x = Y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int dx, int dy)
{
x +=dx;
y +=dy;
}
public String toString()
{
return("X = "+x+" Y= "+y);
}
}
there are lot of problems in your code .when you coding always test current code before go further.
you create a panel and add to the jframe .
JPanel tripanel = new JPanel();
add(tripanel);
but your graphical mechanism has written in move panel so you need to make a move panel instead of jpanel.
keylistners has added to panel but keylisners not get triggered because keylistners work when component is focused . it works for component like jtextfiled . but not for panels .you have to use keybinding .i have added keybind for rightarrow key ..you have to add it to other keys up ,down etc..
also move your paint method from jframe to move jpanel .
example code (run this code and press right arrow ->)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args) {
Test t = new Test();
}
public Test() {
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new move();
add(tripanel);
triangle = new Triangle();
setVisible(true);
}
class move extends JPanel implements MouseListener, MouseMotionListener {
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move() {
addMouseListener(move.this);
addMouseMotionListener(move.this);
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveright");
this.getActionMap().put("moveright", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
triangle.moveTriangle(10, 0);
repaint();
}
});
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if (e.isControlDown()) {
color = Color.RED;
} else {
color = Color.BLACK;
}
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
//System.out.println(e.getPoint());
}
#Override
public void paint(Graphics g) {
super.paint(g);
triangle.drawTriangle(g);
}
}
class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle() {
p1 = new Point(200, 200);
p2 = new Point(170, 230);
p3 = new Point(230, 230);
}
public void moveTriangle(int dx, int dy) {
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g) {
g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY());
g.drawLine(p2.getX(), p2.getY(), p3.getX(), p3.getY());
g.drawLine(p3.getX(), p3.getY(), p1.getX(), p1.getY());
}
}
class Point {
private int x;
private int y;
public Point(int X, int Y) {
x = X;
y = Y;
}
public void setX(int X) {
x = X;
}
public void setY(int Y) {
x = Y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public String toString() {
return ("X = " + x + " Y= " + y);
}
}
}
output >>

Drawing a Image from Thread

I have got application with class extends JPanel. This panel is drawing an Image. here is a code:
public class BackgroundImage extends JPanel{
private BufferedImage img;
private File imageFile;
public BackgroundImage(){
super();
Samolot s1 = new Samolot(200,200,new Dimension(15,15));
s1.start();
imageFile = new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_mapa.jpg");
try {
mapa = ImageIO.read(imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, getWidth(), getHeight(), null);
}
}
What i want to do is a class ball which will be extends Threads.
Each ball will be next thread. Balls need to move, for example from left to right by simply incrementation coordinate int x which defines X-position of created ball.
To show that ball is moving i need to draw an image in current coordinates. after changing position, thread repaint ball to next position. What is more i need to add MouseListener to my ball, to not make problem harder after click it need just to System.out.println("somemessage");
My questions:
where i need to draw my ball? in class Ball? or BackgroundImage? How it should be look like?
where and how add MouseListener to make him works propertly.
how to repaint my panel in every cycle of thread.
here is a code of my Ball class:
class Ball extends Thread {
// The image to display
private BufferedImage img;
private int x;
private int y;
Dimension dim;
public void run() {
super.run();
try {
while(x<1000){
Thread.sleep(300);
x++;
System.out.println(x);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Instantiate the panel and perform initialization
Samolot(int x, int y, Dimension d) {
this.x = x;
this.y = y;
this.dim = d;
try {
img = ImageIO.read(new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_samolot.png"));
} catch (IOException e) { }
}
}
I read that i shouldnt draw anything in other threads then my main thread(here BackgroundImage).
I was thinking about something like that, however it doesnt work:
class Ball:
class Ball extends JComponent implements Runnable {
MouseListener listener;
public void addListener(MouseListener toAdd) {
listener = toAdd;
}
// The image to display
private BufferedImage img;
private int x;
private int y;
Dimension dim;
public void run() {
try {
while(x<1000){
Thread.sleep(300);
x++;
listener.mouseClicked(new MouseEvent(this, 1, 1, 0, x, y, 1, true));
System.out.println(x);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Instantiate the panel and perform initialization
Samolot(int x, int y, Dimension d) {
this.x = x;
this.y = y;
this.dim = d;
try {
img = ImageIO.read(new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_samolot.png"));
} catch (IOException e) { }
}
public BufferedImage getImg(){
return this.img;
}
}
Class BackgroundImage:
public class BackgroundImage extends JPanel implements MouseListener{
private BufferedImage mapa;
private File imageFile;
private Ball s1;
public MapaSwiata(){
super();
s1 = new Ball(200,200,new Dimension(15,15));
Thread t = new Thread(s1);
t.start();
imageFile = new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_mapa.jpg");
try {
mapa = ImageIO.read(imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mapa, 0, 0, getWidth(), getHeight(), null);
g2d.drawImage(s1.getImg(), 200, 200, 15, 15, null);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("message");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}

Pause/Resume java applet

two balls from left and bottom colliding with each other as they meet at a certain coordinate. I have already did what I searched on the internet and it worked perfectly, but I need a start, pause and resume buttons. Look at what I finished :
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class train extends Applet implements Runnable,ActionListener {
private volatile boolean runs = true;
private Image i;
private Graphics doubleG;
Ball b, b2;
Button x,y,z;
Thread thread = new Thread(this);
#Override
public void init(){
setSize(800, 600);
x = new Button("Action!");
y = new Button("Stop");
z = new Button("Resume!");
add(x);
add(y);
add(z);
y.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e)
{
runs = false;
repaint();
}
});
z.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e)
{
try {
runs = true;
b.update(this);
repaint();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
b2.update2(this);
repaint();
}
});
}
#Override
public void start(){
x.addActionListener(this);
b = new Ball(100, 100);
b2 = new Ball(500, 500);
}
#Override
public void run(){
while(runs){
b.update(this);
b2.update2(this);
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
//TODO Auto-generated catch block
// e.printStackTrace();
}
}
}
#Override
public void stop(){
}
#Override
public void destroy(){
}
#Override
public void update(Graphics g) {
// TODO Auto-generated method stub
if(i == null){
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
}
doubleG.setColor(getBackground());
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void paint(Graphics g){
b.paint(g);
b2.paint(g);
}
public void actionPerformed(ActionEvent e) {
thread.start();
}
}
for the main train.class and :
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
public class Ball {
private int x;
private int y;
private double dx = 7.9;
private double dy = 7;
private int radius = 20;
public Ball() {
// TODO Auto-generated constructor stub
}
public Ball(int i, int j) {
// TODO Auto-generated constructor stub
x = i;
y = j;
}
public void update(train sp){
x += dx;
// if(x + dx > sp.getSize().width - 300){
// dx=0;
// }
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.fillOval(x-radius, y-radius, radius * 2, radius * 2);
}
public void update2(train sp){
y -= dy;
if(y - dy < sp.getSize().height - 470){
x += dx;
y -= dy;
// if(y < sp.getSize().height - 470){
// y = sp.getSize().height -470;
// dy *= energyloss;
// dy = -dy;
// }else{
// dy += gravity * dt;
// y += dy*dt + .5 * gravity * dt * dt;
}
//}
}
public void update(ActionListener actionListener) throws InterruptedException {
x += dx;
}
public void update2(ActionListener actionListener) {
train tr = new train();
if(y - dy < tr.getSize().height - 470){
x += dx;
y -= dy;
}else{
y-=dy;
}
}
}
What I want to do is I want to make a resume button. I already finished the start and pause, but when I click the resume button, it just moves 1 coordinate at a time. I need it to just like Start , pause and play normally. Please help. T_T
An easy fix is to not have "runs" control the loop, but just determine whether or not the update method is called. That way you don't break the loop and have to restart.

Categories