why isnt the player appearing on the JFrame? - java

I have this code:
public Juego() {
setFocusable(true);
loop = new Timer(10, this);
loop.start();
jugador = new Jugador(400, 400);
}
public void pintar(Graphics g) {
super.paint(g);
Graphics2D g2D = (Graphics2D) g;
jugador.dibujar(g2D);
}
that is supposed to draw the player into the screen, and this is the code for the actual player:
public class Jugador extends PosicionGlobal {
private String imagendejugador = "/imagenes/jugador.png";
public Jugador(int x, int y) {
super(x, y);
}
public void actualizar() {
}
public void dibujar(Graphics2D g2D) {
g2D.drawImage(imagendejugador(), x, y, null);
}
public Image imagendejugador(){
ImageIcon icono = new ImageIcon(getClass().getResource(imagendejugador));
return icono.getImage();
}
}
When I run it the player doesn't appear its just the same white screen as before. PD: I do have a JFrame and I already add this class to it.
In case its is needed here is the PosicionGlobal class:
public class PosicionGlobal {
public int x;
public int y;
public PosicionGlobal(int x, int y) {
this.x = x;
this.y = y;
}
}

You need to be overriding paint() not pintar()..
change
public void pintar(Graphics g) {
to
#Override public void paint(Graphics g) {
and make sure you call super.paint(g);

Related

Images aren't displaying.. Java

I am trying to make this program that has two images that move in the straight line and when they read the end of frame, they turn their direction... But the thing is, the images aren't appearing on the screen idk why.. Here is my code for Actor class
public class Actor {
private Image img;
private int x,y,width,height;
private final int RIGHT=1,LEFT=-1;
private byte direction=RIGHT;
public Actor(Image img, int x,int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
public Image getImg() {
return img;
}
public void setImg(Image img) {
this.img = img;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public void movement(int frameWidth){
setX(getX()+direction);
if(getX()<0) direction= RIGHT;
if(getX()>(frameWidth-width)) direction= LEFT;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
and here is my main class:
public class game extends JFrame implements Runnable{
private int framewidth=1000;
private int frameheight=1500;
Image image= new ImageIcon("pics/buffy.png").getImage();
Image image2= new ImageIcon("pics/buffythelayer.jpg").getImage();
private Thread thread;
private int picX=100;
private int c=1;
private int xSpeed=3;
private int xFly=1;
private int yFly=100;
private Actor greenCar,pinkCar;
public game(){
setBounds(100,100,framewidth,frameheight);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
thread= new Thread(this);
thread.start();
greenCar=new Actor(image,30,70,98,40);
pinkCar=new Actor(image2,400,70,98,40);
}
public void paint(Graphics g){
g.fillRect(xFly, yFly, 10, 10);
g.drawImage(greenCar.getImg(), greenCar.getX(), greenCar.getY(), null);
g.drawImage(pinkCar.getImg(), pinkCar.getX(), pinkCar.getY(), null);
if(c==2){
g.setColor(Color.CYAN);
g.fillOval(100, 200, 150, 200);
}
}
public static void main(String[] args) {
new game();
}
public void run() {
while(true)
{
xFly++;
greenCar.movement(framewidth);
pinkCar.movement(framewidth);
/*if(picX>280){
xSpeed=-xSpeed;
picX=picX+xSpeed;
c=2;
}
if(picX>=100){
xSpeed=3;
picX=picX+xSpeed;
}*/
repaint();
try{
thread.sleep(13);
}
catch(InterruptedException e){
}
}
}
}
I think I see the problem. When you run the code below, you set the last value, the ImageObserver, to null.
g.drawImage(greenCar.getImg(), greenCar.getX(), greenCar.getY(), null);
g.drawImage(pinkCar.getImg(), pinkCar.getX(), pinkCar.getY(), null);
Instead, you should write it like this:
g.drawImage(greenCar.getImg(), greenCar.getX(), greenCar.getY(), this);
g.drawImage(pinkCar.getImg(), pinkCar.getX(), pinkCar.getY(), this);
Therefore, the JFrame is the object that is notified as the image loads and can be drawn on the screen correctly.
If that's not the case, then you should add super.paint(g) to your paint method.
Your paint(g) method should look like this:
public void paint(Graphics g){
super.paint(g);
g.fillRect(xFly, yFly, 10, 10);
g.drawImage(greenCar.getImg(), greenCar.getX(), greenCar.getY(), this);
g.drawImage(pinkCar.getImg(), pinkCar.getX(), pinkCar.getY(), this);
if(c==2){
g.setColor(Color.CYAN);
g.fillOval(100, 200, 150, 200);
}
}
I hope this helps.
The problem is you run thread before you construct the car object, so
creat object first, the run the thread
greenCar=new Actor(image,30,70,98,40);
pinkCar=new Actor(image2,400,70,98,40);
thread.start();
and you forget set image in Actor constructor
public Actor(Image img, int x,int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.img = img;
}

How to make code move the ball?

I try to make a ping pong game but my ball don't move so how to make the ball is move?
This is my code
package test;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class pingpong1 extends JFrame implements Runnable {
public static void main(String[] args) {
pingpong1 ping = new pingpong1("PingPong Hard Game");
new Thread(ping).start();
ping.setSize(600, 300);
ping.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
ping.setVisible(true);
} private int width, height;
private User user;
private Computer computer;
private Ball ball;
static int UserScore = 0;
int ComputerScore=0;
public pingpong1(String title){
}
#Override
public void paint(Graphics g){
super.paint(g);
Image img2;
ImageIcon img = new ImageIcon("pingpong.png");
img2 = img.getImage();
g.drawImage(img2,0,0, this);
ball.paint(g);
}
#Override
public void run(){
while(true){
ball.moveBall();
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
Logger.getLogger( getName()).log(Level.SEVERE,null,e);
}
}
}
public void paintComponent(Graphics g) {
if (user == null) {
width = getWidth();
height = getHeight();
user = new User();
computer = new Computer();
ball = new Ball();
}
ball.draw(g);
}
public class User{
}
public class Computer{
}
public class Ball{
private int x,y;
private int centerX , centerY;
private Color color;
boolean go;
Ball(){
go=false;
}
public void paint(Graphics g) {
// TODO Auto-generated method stub
}
public Ball(int x,int y,Color color){
this.x=x;
this.y=y;
this.color=color;
this.centerX=5;
this.centerY=5;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void moveBall(){
centerX=5;
x+=centerX;
y+=centerY;
} void draw(Graphics g){
Image img2;
ImageIcon img = new ImageIcon("pingpong.png");
img2 = img.getImage();
g.drawImage(img2, centerX - -35, centerY -10 , null);
}
}
}
Firstly your code for moving it, need to have some sort of input to actually move the ball. Right now it doesn't do anything but add x, y and doesnt repaint it, so you basically tell it to do nothing.
if you are looking for user controlled something like this will work?
public void moveIt(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
myY += 5;
break;
case KeyEvent.VK_UP:
myY -= 5;
break;
case KeyEvent.VK_LEFT:
myX -= 5;
break;
case KeyEvent.VK_RIGHT:
myX += 5;
break;
}
}
If you are looking for a way to move the ball automatically, then you will need to look at a few things in your code. As you don't take in to consideration the speed/ direction etc...
This is a basic example of a moving ball http://introcs.cs.princeton.edu/java/34nbody/Ball.java.html
I would of made a comment but my rep is under 50.
In your code you are correctly updating the ball's position in your game loop:
class pingpong1
while(true){
ball.moveBall(); // You update movement here
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.err.println("Interrupted.");
}
}
But you never actually redraw the ball at the updated position:
public void paint(Graphics g){
super.paint(g);
Image img2;
ImageIcon img = new ImageIcon("pingpong.png");
img2 = img.getImage();
g.drawImage(img2,0,0, this);
ball.paint(g); // this method is empty
}
Because the ball method paint is empty:
class Ball
public void paint(Graphics g) {
// TODO Auto-generated method stub
}
To correct that:
public void paint(Graphics g) {
ImageIcon icon = new ImageIcon("ball.png");
Image image = icon.getImage();
g.drawImage(image, x, y, null);
}
Or just call ball.draw() instead but you still have to correct the x and y because they are currently constant, change:
g.drawImage(img2, centerX + 35, centerY - 10, null);
To:
g.drawImage(img2, x, y, null);

Java Image Drawing

I'm in the process of making a simple 2-D game, however I am having trouble drawing images. Below are a few classes that are relevant to the problem
private Vector<Bullet> ammo = new Vector<Bullet>(100);
public class Bullet{
Image img;
int x, y, speed;
boolean show;
Bullet(Image img,int x, int y, int speed, boolean show){
this.x = x;
this.y = y;
this.speed = speed;
this.img = img;
this.show = show;
}
public void draw(ImageObserver obs) {
if(show)
g2.drawImage(img, this.x, this.y, obs);
}
public void update(){
this.y -= 1;
}
}
public class Movement{
....
Movement(....){
.....
}
public void fly(){
......
ammo.add(new Bullet(bullet1, m.x, m.y, 7, true));
}
public class MyPlane {
KeyControl key;
Movement flight;
Image img;
int x, y, speed, move = 0;
int boom;
...
}
public void drawDemo() {
...
for(Bullet bullets: ammo)
bullets.update();
...
for(Bullet bullets: ammo)
bullets.draw(this);
}
}
When I call bullets.draw(this) nothing actually is drawn on the screen. I know however that the ammo vector does contain the correct information, such as the x coordinate, y coordinate... I'm using Graphics 2-D by the way. Any help and or suggestions would be greatly appreciated thanks.
public void paint(Graphics g) {
if(bimg == null) {
Dimension windowSize = getSize();
bimg = (BufferedImage) createImage(windowSize.width,
windowSize.height);
g2 = bimg.createGraphics();
}
drawDemo();
g.drawImage(bimg, 0, 0, this);
}
I think you should draw the image like this:
public void draw(Graphics g2) {
if(show)
g2.drawImage(img, this.x, this.y, null);
}
Then in your plane class you have to add Graphics as an argument of the drawDemo() method:
public void drawDemo(Graphics g2) {
...
for(Bullet bullets: ammo)
bullets.update();
...
for(Bullet bullets: ammo)
bullets.draw(g2);
}
}
and finally in you paint(Graphics g) method you call this:
public void paint(Graphics g) {
/*
...
*/
drawDemo(g2);
g.drawImage(bimg, 0, 0, this);
}

Circle collision detection

I have created a program that drawing 2 circle on the screen and using keyboard ASWD and arrow key to move around..here is the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BallObject {
private int x;
private int y;
private int radius;
BallObject() {
x=0;
y=0;
radius=0;
}
BallObject (int x,int y,int radius) {
this.x=x;
this.y=y;
this.radius=radius;
}
public void setX(int x) {this.x=x;}
public void setY(int y) {this.y=y;}
public void setRadius(int r) {radius=r;}
public int getX() {return x;}
public int getY() {return y;}
public int getRadius() {return radius;}
}
class Ball extends JFrame implements KeyListener {
BallObject ball1;
BallObject ball2;
Ball() {
super("Simple Ball");
setSize(800,600); //set screen resolution
ball1 = new BallObject(getWidth()/2,getHeight()/2,20);
ball2 = new BallObject(40,40,20);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fill(new Rectangle(0,0,800,600));
//drawing ball1
g2d.setColor(Color.RED);
g2d.fillOval(ball1.getX(),ball1.getY(),ball1.getRadius()*2,ball1.getRadius()*2);
//drawing ball2
g2d.setColor(Color.GREEN);
g2d.fillOval(ball2.getX(),ball2.getY(),ball2.getRadius()*2,ball2.getRadius()*2);
}
public static void main (String args[]) {
new Ball();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT)
ball1.setX(ball1.getX()-2);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
ball1.setX(ball1.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_UP)
ball1.setY(ball1.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_DOWN)
ball1.setY(ball1.getY()+2);
if(e.getKeyCode()==KeyEvent.VK_A){
ball2.setX(ball2.getX()-2);
//System.out.println("Hello");
}
if(e.getKeyCode()==KeyEvent.VK_D)
ball2.setX(ball2.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_W)
ball2.setY(ball2.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_S)
ball2.setY(ball2.getY()+2);
repaint();
}
//redraw the screen to show the updated ball location
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
Now i need to test the collision..Once two balls are touching each other.it will show a message "COLLISION DETECTED"..pls help...
Isn't it simply: if the distance of both center points is less or equal to the sum of the radiuses, then there is a collision?

Java - draw graphics using a method and a constructor

I am working on a java 2d game library. I want a method named paintImage() to do graphics.drawImage() every time paintImage() is called.
public void paintImage(image1, x, y){
//i want it to run graphics.drawImage every time it is called.
}
public void anotherMethod(){
paintImage(...);
paintImage(...);
//paint as many times as i want.
}
public void paintComponent(Graphics graphics){
graphics.drawImage();
super.paintComponents();
}
Thanks for your time and please leave a suggestion, sorry but its kind of hard to explain this.
For Single Image Display
public class DrawingDemo {
private JPanel panel;
private MyImage imageData;
public DrawingDemo() {
...
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (imageData != null) {
g.drawImage(imageData.getImage(), imageData.getX(), imageData.getY(), this);
}
}
};
...
}
public void paintImage(Image image1, int x, int y) {
imageData = new MyImage(image1, x, y);
panel.repaint();
}
public void anotherMethod() {
paintImage(...);
paintImage(...);
}
}
public class MyImage { // bean class for storing image information
private Image image;
private int x;
private int y;
public MyImage(Image image, int x, int y) {
this.image = image;
this.x = x;
this.y = y;
}
public Image getImage(){
return image;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
... you can add setter methods
}
UPDATE : For multiple image display
private JPanel panel;
private ArrayList<MyImage> imageData; // or any other data structure you like
public DrawingDemo() {
imageData = new ArrayList<>();
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (MyImage myImage : imageData) {
g.drawImage(myImage.getImage(), myImage.getX(), myImage.getY(), this);
}
}
};
frame.add(panel);
frame.setVisible(true);
}
public void paintImage(Image image1, int x, int y) {
imageData.add(new MyImage(image1, x, y));
panel.repaint();
}
public void anotherMethod() {
paintImage(new ImageIcon("/home/blackadmin/Desktop/image.jpg").getImage(), 0, 0);
paintImage(new ImageIcon("/home/blackadmin/Desktop/image2.jpg").getImage(), 50, 50);
paintImage(new ImageIcon("/home/blackadmin/Desktop/image3.jpg").getImage(), 100, 100);
}
OUTPUT :
Have a look at this answer
Comment if you don't understand anything, hope this will help
What I think you're looking to do is to make changes to some states in your class and then redrawing your images with changes based on those state changes -- in other words perhaps you're looking to do animation. If so, then your image drawing should all be done either within the paintComponent method using its Graphics object, or in another method called by paintComponent one that uses the Graphics object passed into paintCocalzmponent. This can be done by passing a Graphics parameter into the other method. Your anotherMethod would then request that the JVM repaint the GUI by calling repaint(). For example:
public void anotherMethod() {
x++;
y++;
repaint(); // this will stimulate JVM to call paint/paintComponent
}
private void paintImage(Graphics g, BufferedImage img, int x, int y2) {
g.drawImage(img, x, y2, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintImage(g, image1, x, y);
}
A complete example of this is as follows:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.Transient;
import javax.swing.*;
public class PaintEg extends JPanel {
private static final int IMG_W = 30;
private static final int IMG_H = IMG_W;
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int TIMER_DELAY = 20;
private BufferedImage image1;
private int x;
private int y;
public PaintEg() {
image1 = createImg();
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
anotherMethod();
}
}).start();
}
private BufferedImage createImg() {
BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setBackground(Color.red);
g2.clearRect(0, 0, IMG_W, IMG_H);
g2.setColor(Color.blue);
g2.fillRect(IMG_W / 4, IMG_H / 4, IMG_W / 2, IMG_H / 2);
g2.dispose();
return img;
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void anotherMethod() {
x++;
y++;
repaint(); // this will stimulate JVM to call paint/paintComponent
}
private void paintImage(Graphics g, BufferedImage img, int x, int y2) {
g.drawImage(img, x, y2, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintImage(g, image1, x, y);
}
private static void createAndShowGUI() {
PaintEg paintEg = new PaintEg();
JFrame frame = new JFrame("PaintEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Categories