Jumping square. thread. Prevent from jumping several times - java

I am trying to implement a jumping square. The square should not be able to jump several times like in flappy bird but have to return on its baseYPosition or - to be implemented later - on a platform(simple GeometryDash clone for a school project).
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Square extends JPanel implements ActionListener, KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private int threadDelay = 40;
public int squareYPosition = 400,squareXPosition = 400, baseYPosition = 400;
public int jumpyness = 40, gravity=3, ySpeed, counter = 0;
public boolean isJumping;
public Square(){
Timer t = new Timer(threadDelay, this);
t.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(squareXPosition, squareYPosition, 40, 40);
}
public void jump(){
ySpeed = jumpyness;
System.out.println("squareYPosition before while: "+squareYPosition);
System.out.println("jumping before?"+isJumping);
if(!isJumping){
isJumping = true;
System.out.println("was not jumping before?"+isJumping);
new Thread(){
#Override
public void run(){
while(isJumping && (ySpeed!=0 || squareYPosition < baseYPosition)){
if(squareYPosition < 0){
ySpeed=-1;
squareYPosition = 0 ;
}
System.out.println("squareYPosition: "+squareYPosition+" . ySpeed: "+ySpeed);
if(squareYPosition-ySpeed > baseYPosition && counter>(jumpyness/gravity)){
squareYPosition = baseYPosition;
ySpeed = 0;
counter = 0;
isJumping = false;
System.out.println("set ySpeed to 0");
}
else{
squareYPosition = squareYPosition - ySpeed;
ySpeed = ySpeed - gravity;
counter++;
}
try {
Thread.sleep(threadDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()){
case KeyEvent.VK_SPACE:
this.jump();
break;
case 38:
this.jump();
break;
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
}
The Square class is instantiated in and added to a JFrame.
MainFrame.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private Square square;
public MainFrame(String text, GraphicsDevice device, DisplayMode displayMode){
setTitle(text);
setUndecorated(true);
square = new Square();
add(square);
//pack();
setVisible(true);
device.setFullScreenWindow(this);
device.setDisplayMode(displayMode);
repaint();
addKeyListener(square);
}
}
PeterTest.java
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.util.Timer;
import java.util.TimerTask;
public class PeterTest {
static long revalidateDelay = 30;
static final int ELEMENTESTART = 3; // Elemente +1 f�r L�cken/abstand oben/unten
public static void main(String[] args) {
GraphicsEnvironment enivronment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = enivronment.getDefaultScreenDevice();
DisplayMode[] ds = device.getDisplayModes();
//The following is necessary because Unix and Windows have reversed orders in DisplayMode
int highestResolutionIndex = getHighestResolutionIndex(ds);
DisplayMode displayMode = new DisplayMode(ds[highestResolutionIndex].getWidth(), ds[highestResolutionIndex].getHeight(), ds[highestResolutionIndex].getBitDepth(), ds[highestResolutionIndex].getRefreshRate());
MainFrame frame = new MainFrame("Test", device, displayMode);
//
}
public static int getHighestResolutionIndex(DisplayMode[] ds){
long pixels = ds[ds.length-1].getWidth() * ds[ds.length-1].getHeight();
int highestResolutionIndex = 0;
for(int i = 0; i<ds.length; i++){
long newpixels = ds[i].getWidth() * ds[i].getHeight();
if(newpixels>=pixels){
highestResolutionIndex = i;
pixels = newpixels;
}
}
return highestResolutionIndex;
}
}
The boolean isJumping should prevent the thread to be opened while there is another thread for the jumping, but holding the space key will let the square hit the top of the frame. Even locking the boolean will not work for me. I have no idea how to fix this :(
Please help me :'(

Found the problem myself. It hurts. The problem was setting the ySpeed to jumpyness in the first line of jump() and not in the thread before the while.

Related

KeyListener wont change variable

I have been working on this snake project, and dont really understand why the keylistener isnt actually changing the variable char key. I have some other examples of keylisteners, and they all work properly, but for some reason mine isnt working. Some help would be appreciated. Thanks a lot for the help.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
public class Main extends JPanel implements Runnable {
/*
*
* SIZE OF BOARD
*
*/
static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
static GraphicsDevice[] gs = ge.getScreenDevices();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private static final int DIM_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
private static final int DIM_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static Snake s = new Snake();
static Main main = new Main();
KeyListener listener = new Snake();
boolean black = true;
public Main() {
addKeyListener(listener);
}
#SuppressWarnings("deprecation")
public static void main(String[] args) {
//gs[0].setFullScreenWindow(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setCursor(Cursor.CROSSHAIR_CURSOR);
frame.setSize(DIM_WIDTH, DIM_HEIGHT);
frame.add(main);
frame.setVisible(true);
(new Thread(new Main())).start();
}
// paints the panel
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
/*
* Snake
*/
//Redraws Background
g2d.setColor(Color.black);
g2d.fillRect(0, 0, (int) screenSize.getWidth(), (int) screenSize.getHeight());
//Draws Border
g2d.setColor(Color.white);
g2d.fillRect(0,0, (int)screenSize.getWidth(), 1);
g2d.fillRect(0,0, 1, (int)screenSize.getHeight());
g2d.fillRect((int)screenSize.getWidth()-1, 1, 1, (int)screenSize.getHeight());
g2d.fillRect(0, (int)screenSize.getHeight()-86, (int)screenSize.getWidth(), 10);
//Draws Snake head
g2d.setColor(s.getColor());
g2d.fillRect(s.getX(), s.getY(), 30, 30);
}
// Creates Frame, and starts the game
#Override
public void run() {
while (!s.getIsDead()) {
move();
}
}
public void move() {
s.move();
s.death();
main.repaint();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Thread.interrupted()) {
return;
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Snake implements KeyListener {
Color c = Color.green;
//Starting position of Snake
int x = 50;
int y = 50;
char key;
boolean dead = false;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public void move() {
x++;
}
public void death() {
if (x + 30 >= screenSize.getWidth() || y + 115 >= screenSize.getHeight() || y<=0 || x<=0) {
c = Color.red;
dead = true;
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Color getColor() {
return c;
}
public boolean getIsDead() {
return dead;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
key = 'w';
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Change your constructor to
public Main() {
addKeyListener(listener);
setFocusable(true);
requestFocus();
}
But take a look at this question, you should not use KeyListeners.
java keylistener not called
As #azurefrog mentioned, your keyPressed method is setting key to 'w' every time. You need to use the KeyEvent passed in as a parameter to that method to get the key that was pressed. Your keyPressed method should look something like this:
#Override
public void keyPressed(KeyEvent e) {
key = e.getKeyChar();
}

how do i make a JPanel background that won't update?

I'm trying to make an animated screensaver with some changing colors and moving shapes and I also want it to have a sort of trail effect (like how the most recent color on each pixel is continually drawn there if you don't set your background color). I achieved this effect once before, but I don't know how I did it. Currently the result is a moving square with that changes colors across a grey background.
ScreenSaver.java
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ScreenSaver extends JPanel
{
public static Component sc;
public int delay = 1000/2;
public int state = 0;
public int re = 255;
public int gr = 0;
public int bl = 0;
public int d = 1;
ScreenSaver()
{
ActionListener counter = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
updateUI();
repaint();
}
};
new Timer(delay, counter).start();
System.out.println("this is the secret screensaver that appears after 30 seconds of no mouse activity");//i have this line here so it doesn't print every time the screen updates
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(null);
if (state == 0)
{
gr++;
if(gr == 255)
state = 1;
}
if (state == 1)
{
re--;
if(re == 0)
state = 2;
}
if (state == 2)
{
bl++;
if(bl == 255)
state = 3;
}
if (state == 3)
{
gr--;
if(gr == 0)
state = 4;
}
if (state == 4)
{
re++;
if(re == 255)
state = 5;
}
if (state == 5)
{
bl--;
if(bl == 0)
state = 0;
}
g.setColor(new Color(re, gr, bl));
d++;
g.fillRect(d, 50, 50, 50);
}
public static void main(String[] args)
{
//ScreenSaver sc = new ScreenSaver();
}
}
Main.java: (ScreenSaver.java is called as an object through this file)
import java.awt.Color;
import java.awt.Graphics;
//import java.util.Random;
//import javax.swing.AbstractAction;
//import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.Timer;
public class FinalProject extends JPanel implements MouseMotionListener
{
public int delay = 1000/2;
public boolean screenActive = true;
public int why = 1;
FinalProject()
{
ActionListener counter = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
updateUI();
repaint();
}
};
new Timer(delay, counter).start();
}
static JFrame jf = new JFrame();
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.BLACK);
if (screenActive)
{
why++;
}
if (why == 6)
{
why = 0;
System.out.println("inactivity detected");
screenActive = false;
ScreenSaver sc = new ScreenSaver();
jf.add(sc);
}
}
public static void main(String[] args) throws InterruptedException
{
System.out.println("Welcome to Computer Simulator 0.1");
System.out.println("this is the main screen");
FinalProject e = new FinalProject();
//ScreenSaver sc = new ScreenSaver();
jf.setTitle("game");
jf.setSize(500,500);
//jf.setUndecorated(true);
//jf.setBackground(new Color(1.0f,1.0f,1.0f,0.5f));
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//jf.add(new ScreenSaver());
jf.add(e);
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent MOUSE_MOVED)
{
}
}
Don't invoke updateUI(). All you need is the repaint() to cause the component to repaint itself.
One way it to do the drawing to a BufferedImage and then use the BufferedImage to create an ImageIcon which you add to a JLabel.
The other way is to keep a list of object that you want to paint and then just iterate through the list each time the component is repainted.
Check out Custom Painting Approches for working examples and an analysis of when you might use either approach.

Can't figure out how to repaint

So I have this little project where I make the mario jump. But I can't figure out how to repaint it. If I do it in the Main class after a click, then the whole jumping will be very jerky.
I tried to do it at the end of my jump function but that did not work too.
Here is my code:
Main:
package klassid;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Main extends JComponent implements KeyListener, ActionListener{
static Hero hero;
Timer t = new Timer(500,this);
public static void main(String[] args) {
JFrame aken = new JFrame("Simple jumping simulator");
aken.setSize(600, 600);
aken.getContentPane().setBackground(new Color(255,255,255));
aken.getContentPane().add(new Main());
aken.setVisible(true);
aken.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hero.the_jump();
}
public Main(){
addKeyListener(this);
setFocusable(true);
t.start();
hero = new Hero(0, 320);
}
public void paintComponent(Graphics g){
hero.render(g, this);
g.setColor(Color.GREEN);
g.fillRect(0, 550, 600, 2);
}
#Override
public void keyPressed(KeyEvent e) {
hero.move(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
hero.move2(e.getKeyCode());
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {}
}
And my Hero class:
package klassid;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Graphics;
public class Hero {
static Main main;
int y;
Image pilt = Toolkit.getDefaultToolkit().getImage("../mario.png");
private double height = 0, speed = 4;
public static final double gravity = 9.81;
private double x = 25;
private boolean left = false, right = false, up = false;
public Hero(int x, int y){
this.x = x;
this.y = y;
}
public void render(Graphics g, Main pohiKlass){
g.drawImage(pilt, (int) (x), (int) (500-(height*100)), 50, 50, pohiKlass);
}
public void the_jump() {
long previous = 0, start = 0;
while(true){
start= System.nanoTime();
if(previous != 0 && up){
double delta = start - previous;
height += (delta/1000000000) * speed;
speed -= (delta/1000000000) * gravity;
}
if(left)
x -= 3;
if(right)
x += 3;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(height < 0){
height = 0;
speed = 4;
up = false;
}
previous = start;
repaint();
}
}
public void move(int i){
if(i == 38)
up=true;
if(i == 37)
left=true;
if(i == 39)
right=true;
}
public void move2(int i){
if(i == 37)
left=false;
if(i == 39)
right=false;
}
}
I also tried to access the paintComponent in the_jump function but it did not work as I have no idea what kind of a parameter it expects.
How is this mess solvable?
The first line in your paintComponent method should be:
super.paintComponent(g);
JComponent will do a lot of things for you, but you need to explicitly call the super class method to do so. Take a look at the Oracle Documentation here.
You could call repaint() in your actionPerformed method, if you decrease the timer value to something very low. This will give you "continuous" repainting (as many times a second as you can reasonably perform).

key listener not working for some reason

i made this code that when you start it it's suposed to show you an image and then change it between other two images when you press the left or right key, but for some reason it isn't reading the input from the keyboard, i tryed to use a mouseListener and it worked, this is the code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Implementary extends JFrame
{
private static final long serialVersionUID = 1L;
public Dimension d;
public static ImageIcon Im = new ImageIcon(Implementary.class.getResource("death.png"));
public static ImageIcon Imc = new ImageIcon(Implementary.class.getResource("right.png"));
public static ImageIcon I = new ImageIcon(Implementary.class.getResource("left.png"));
public static Image Img = Im.getImage();
public static int x = 10;
public static int y = 10;
public Implementary()
{
super("hue");
int x1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int y1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
d = new Dimension(x1, y1 - 45);
this.setSize(d);
this.setLocationRelativeTo(null);
Panel p = new Panel();
p.addKeyListener(new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
keyPressed(e);
}
#Override
public void keyPressed(KeyEvent e)
{
int k = e.getKeyCode();
if (k == KeyEvent.VK_LEFT)
{
Img = I.getImage();
repaint();
System.out.println(3);
}
else
{
Img = Imc.getImage();
repaint();
System.out.println(2);
}
System.out.println(1);
}
#Override
public void keyReleased(KeyEvent e)
{
keyPressed(e);
}
});
this.add(p);
}
static class Panel extends JPanel
{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.cyan);
g.drawImage(Img, x, y, null);
}
}
}
and this is the main class:
public class Yo
{
public static void main(String args[])
{
Implementary imp = new Implementary();
imp.setVisible(true);
}
}
Adding the KeyListener to the whole JFrame could do the trick.
As your JPanel cannot be selected/focused it doesn't receive keystrokes.
Changing
p.addKeyListener(new KeyListener()
to
this.addKeyListener(new KeyListener()
works for me.

Draw Multiple objects in java?

Hey guy's im making a java game where yellow blocks appear randomly across the game screen and you have to collect them. These objects are created from one class and i was wondering if there is a way to draw all of them?
This is the code that spawns them:
package OurGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class coins extends JPanel implements ActionListener {
Timer t;
coin c;
public coins() {
t = new Timer(1000,this);
t.start();
}
public void actionPerformed(ActionEvent e) {
System.out.println("1 Second");
Random rx = new Random();
Random ry = new Random();
c = new coin(rx.nextInt(640),ry.nextInt(480));
}
}
and this is the code for the coin itself.
package OurGame;
import java.awt.Image;
import javax.swing.ImageIcon;
public class coin {
Image coin;
int x,y;
public coin(int x1, int y1) {
ImageIcon i = new ImageIcon("C:/coin.png");
coin = i.getImage();
x = x1;
y = y1;
}
public Image getImage(){
return coin;
}
public int getX(){
return x;
}
public int getY() {
return y;
}
}
Would be awesome if you could help.
Why not create an ArrayList of Coin (class names should be capitalized) or ArrayList. Then if you need to add or remove a Coin from the display, you would add or remove it from the ArrayList. Then the paintComponent method could iterate through the array list in a for loop drawing each coin in the loop.
Also, The simplest way to display a Coin would be to put it into an ImageIcon and then use that to set a JLabel's icon.
e.g. with image scaling to make coin smaller and with image filter to change white background to transparent:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Coins extends JPanel implements ActionListener {
private static final String COIN_URL_PATH = "http://cdn.dailyclipart.net/wp-content/uploads/medium/clipart0273.jpg";
private static final String COIN_URL_PATH2 = "http://content.scholastic.com/content/media/products/71/0439510171_rgb15_xlg.jpg";
private static final String COIN_URL_PATH3 = "http://uscoinstoday.com/images/e/130580876887_0.jpg";
private static final int PAN_WIDTH = 900;
private static final int PAN_HT = 700;
protected static final int TRANSPARENT = new Color(255, 255, 255, 0)
.getRGB();
private Timer t;
private BufferedImage coinImage;
private ImageIcon coinIcon;
private Random random = new Random();
public Coins() {
setLayout(null);
try {
coinImage = ImageIO.read(new URL(COIN_URL_PATH));
double scaleFactor = 0.35;
BufferedImage destImg = new BufferedImage((int)(coinImage.getWidth() * scaleFactor),
(int) (coinImage.getHeight() * scaleFactor), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
AffineTransformOp ato = new AffineTransformOp(at,
AffineTransformOp.TYPE_BICUBIC);
ato.filter(coinImage, destImg);
ImageFilter whiteToTranspFilter = new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
Color color = new Color(rgb);
int colorSum = color.getBlue() + color.getRed() + color.getGreen();
int maxColorSum = 600;
if (colorSum > maxColorSum ) {
return TRANSPARENT;
}
return rgb;
}
};
ImageProducer ip = new FilteredImageSource(destImg.getSource(), whiteToTranspFilter);
Image destImg2 = Toolkit.getDefaultToolkit().createImage(ip);
coinIcon = new ImageIcon(destImg2);
t = new Timer(1000, this);
t.start();
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PAN_WIDTH, PAN_HT);
}
public void actionPerformed(ActionEvent e) {
System.out.println("1 Second");
Coin c = new Coin(random.nextInt(640), random.nextInt(480), coinIcon);
add(c.getCoinLabel());
revalidate();
repaint();
}
public static void main(String[] args) {
Coins coins = new Coins();
JFrame frame = new JFrame("Coins");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(coins);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Coin {
JLabel coinLabel = new JLabel();
public Coin(int x1, int y1, ImageIcon coinIcon) {
coinLabel.setIcon(coinIcon);
coinLabel.setLocation(x1, y1);
coinLabel.setSize(coinLabel.getPreferredSize());
}
public JLabel getCoinLabel() {
return coinLabel;
}
}
You have two options:
1) Save a list of all coins and override the paintComponent() method for your JPanel and call rePaint() after a coint is added.
2) Coin could extend some JComponent which provides a paintComponent method; then you could call this.add( ... ) in you JPanel; and this.rePaint().
Some side note:
1) Your Image should be static; otherwise there is an Image for every coin; although it's the same image.
Example code:
package OurGame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class coins extends JPanel implements ActionListener {
private Timer t;
private ArrayList<Coin> coins = new ArrayList<Coin>();
public coins() {
t = new Timer(1000,this);
t.start();
}
public void actionPerformed(ActionEvent e) {
System.out.println("1 Second");
Random rx = new Random();
Random ry = new Random();
this.coins.add(new Coin(rx.nextInt(640),ry.nextInt(480)));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(Coin coin : this.coins) {
g.drawImage(coint.getImage(), coin.getX(), coint.getY(), observer);
}
}
}

Categories

Resources