Inserting certain code into a custom class... How? - java

I am trying to write a sprite class, however it isn't in just one class, where I made a whole working class and just declared a few variables (this is what I am trying to achieve.), but rather... a half-done class, with a procedure, and I would like to "insert" that procedure, or what is inside.
Here is the code of the half-done class (with variables already added):
package testowhat;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Sprite extends Component {
Sprite(String image1) throws IOException, InterruptedException{
playerConstructor(image1);
}
Integer imgPosX; Integer imgPosY;
Integer divideSize2; Integer divideSize1;
Integer Height; Integer Width;
Integer numberOfSpriteCells, numberOfSpriteLayers, numberOfCellsInALine, heightOfCells, widthOfCells, countingNumber1, countingNumber2;
BufferedImage player;
String image;
JPanel playerPanel = new JPanel() {
public void paint(Graphics g) {
g.drawImage(player.getScaledInstance(player.getWidth()/divideSize1, player.getHeight()/divideSize2, Image.SCALE_DEFAULT), imgPosX, imgPosY, null);
}
};
private void playerConstructor(String image) throws IOException, InterruptedException {
try {
player = ImageIO.read(new File(image));
} catch (IOException ex) {System.out.println("File is missing.");}
//----------------------------------------------------------------------
Height = player.getHeight()+10;
Width = player.getWidth()+10;
//----------------------------------------------------------------------
playerPanel.setLocation(this.getLocation());
playerPanel.setSize(this.getHeight(), this.getWidth());
//----------------------------------------------------------------------
playerPanel.setMinimumSize(new Dimension(Height, Width));
playerPanel.setMaximumSize(new Dimension(Height, Width));
//----------------------------------------------------------------------
if (this.isVisible() == true) {
playerPanel.setVisible(true);
}
//----------------------------------------------------------------------
}
}
And now here is what is inside the procedure:
for (number2=1; number2<7; number2++) {
doChange();
Thread.sleep(100);
sprite.repaint();
sprite.playerPanel.repaint();
if (number2 <= 7) {
number2 = 1;
}
}
.....
//--------------------------------------------------------------------------
private void doChange() {
sprite.imgPosX = sprite.imgPosX - 103;
number = number + 1;
sprite.repaint();
sprite.playerPanel.repaint();
if (number==3) {
sprite.imgPosY = sprite.imgPosY - 89;
sprite.imgPosX = 0;
}
if (number==6) {
number = 0;
sprite.imgPosX = 0;
sprite.imgPosY = 0;
sprite.repaint();
sprite.playerPanel.repaint();
}
}

Related

How can I scale my game for different resolutions while using MVC

I want to be able to scale my game for different resolutions, but I'm only allowed to work in the controller (I'm using MVC). I'm not sure how to make my game scale.
I haven't really tried anything yet since I'm not familiar with scaling games for different resolutions. Is there a special function for that?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.util.Collection;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import se.egy.game.resourses.Drawable;
import se.egy.game.resourses.GameCloseException;
public class GameScreen{
private int height, width;
private String title;
private boolean fullScreenMode = false;
private JFrame jf;
private GraphicsDevice device;
private BufferStrategy backBuffer;
private Graphics2D g;
private Color bgColor = Color.BLACK; // Svart, default som bakgrund
private Image bgImg = null;
private DisplayMode oldDM = null;
public GameScreen(String title, int width, int height, boolean fulScreenMode) {
this.width = width;
this.height = height;
this.title = title;
this.fullScreenMode = fulScreenMode;
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
createWindow();
}
});
}catch(Exception e) {}
clearScreen();
if(fullScreenMode) { // Ful lösning ;-)
jf.setBounds(0, 0, width, height);
try{ Thread.sleep(50);}catch(Exception e){}
}
}
public GameScreen(String title, int width, int height) {
this(title, width, height, false);
}
private void createWindow() {
jf = new JFrame(title);
if(fullScreenMode) {
DisplayMode dm = new DisplayMode(width, height, 32, 0);
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = env.getDefaultScreenDevice();
jf.setUndecorated(true);
jf.setBounds(0, 0, width, height);
oldDM = device.getDisplayMode();
device.setFullScreenWindow(jf);
device.setDisplayMode(dm);
}else {
jf.setSize(new Dimension(width, height));
jf.setResizable(false);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
jf.setIgnoreRepaint(true);
jf.setVisible(true);
jf.requestFocus();
jf.createBufferStrategy(2);
backBuffer = jf.getBufferStrategy();
}
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.ImageIcon;
import se.egy.game.model.Entity;
import se.egy.game.model.Sprite;
import se.egy.game.view.GameScreen;
import se.egy.game.view.TxtEntity;
public class GameController implements KeyListener{
private GameScreen gs;
private boolean gameRunning = true;
private int fps;
private Entity player;
private ArrayList<Entity> entityList = new ArrayList<>();
private HashMap<String, Boolean> keyDown = new HashMap<>();
public GameController(GameScreen gs, int fps) {
this.gs = gs;
this.gs.setKeyListener(this);
this.fps = fps;
resetkeyDown();
loadObjects();
}
public void runGame() {
long renderDelay = 1000000000/fps;
long lastUpdateTime = System.nanoTime();
while(gameRunning) {
long deltaTime = System.nanoTime() - lastUpdateTime;
if(deltaTime >= renderDelay) {
lastUpdateTime = System.nanoTime();
gs.render(entityList);
update(deltaTime);
}
}
}
I want the game to work for different resolutions. So that my "enemies", as well as the player, is on the same position for a 1920 x 1080 resolution as an 800 x 600 resolution. There is a bit more code to both the GameScreen(view) and to the GameController(controller), but I don't think it's necessary to show more. My model is only of the entities that I'm using for the game, such as the player and the enemies.

Java - Objects won't go off screen (top- & leftside only)

I am trying to "teleport" objects to the opposite positions whenever they get out of screen. I've managed to do this with right & bottom sides, but for some reason, which I haven't figured out, the star objects won't go off screen on TOP & LEFT sides UNLESS the lerping speed is high enough.
Preview:
Main.java
package asteroids;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Main extends Canvas implements KeyListener {
private boolean gameOver;
private BufferStrategy backBuffer;
private Dimension dimension = new Dimension(Config.WINDOW_WH[0], Config.WINDOW_WH[1]);
private List<Star> stars = new ArrayList<Star>();
private HashMap<Integer,Boolean> keyDownMap = new HashMap<Integer, Boolean>();
private Ship ship;
private Image bg;
private float starGoalX, starGoalY;
public Main() {
// Initialize Window
initWindow();
addKeyListener(this);
this.createBufferStrategy(2);
backBuffer = this.getBufferStrategy();
bg = new ImageIcon(getClass().getResource("/bg.png")).getImage();
// init variables
gameOver = false;
// Generating stars
generateStars();
// Init spaceship
ship = new Ship(25,36,"ship.png");
// Init loop
gameLoop();
}
public void initWindow(){
JFrame window = new JFrame("Asteroids");
setPreferredSize(dimension);
window.add(this);
window.pack();
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.requestFocus();
}
public float lerp(float starGoal, float vel, float speed) {
return starGoal + speed * (vel - starGoal);
}
public void update() {
if(keyDownMap.containsKey(KeyEvent.VK_ESCAPE)){
gameOver = false;
System.exit(0);
}
for(Star s: stars) {
s.posx += lerp(this.starGoalX, s.velX, Config.lerpSpeed);
s.velX += this.starGoalX * Config.lerpSpeed;
s.posy += lerp(this.starGoalY, s.velY, Config.lerpSpeed);
s.velY += this.starGoalY * Config.lerpSpeed;
checkPos(s);
s.update();
}
}
public void checkPos(Star s) {
if(s.posx < -s.width)
s.posx = Config.WINDOW_WH[0]-s.width;
else if(s.posx > Config.WINDOW_WH[0])
s.posx = 0;
if(s.posy < -s.height)
s.posy = Config.WINDOW_WH[1]-s.height;
else if(s.posy > Config.WINDOW_WH[1])
s.posy = 0;
}
public void render(){
Graphics2D g = (Graphics2D) backBuffer.getDrawGraphics();
if (!backBuffer.contentsLost()) {
g.drawImage(this.bg,0,0,Config.WINDOW_WH[0], Config.WINDOW_WH[1], null);
// Draw Stars
g.setColor(Color.WHITE);
for(Star s: stars)
g.fillOval(s.posx - (s.width/2), s.posy - (s.height/2), s.width, s.height);
// Draw ship
g.drawImage(
this.ship.getImage(),
this.ship.posx, this.ship.posy,
this.ship.width, this.ship.height, null);
backBuffer.show();
g.dispose();
}
}
public void generateStars() {
for(int i = 0;i < 50;i++) {
int starX = new Random().nextInt(Config.WINDOW_WH[0]+100)+5;
int starY = new Random().nextInt(Config.WINDOW_WH[1]+100)+5;
stars.add(new Star(starX, starY));
}
}
public void gameLoop(){
while(!gameOver){
update();
render();
try{ Thread.sleep(20);}catch(Exception e){};
}
}
public static void main(String[] args) {
new Main();
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) this.starGoalX = Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) this.starGoalX = -Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_UP) this.starGoalY = Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_DOWN) this.starGoalY = -Config.lerpSpeed;
keyDownMap.put(e.getKeyCode(), true);
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT
|| e.getKeyCode() == KeyEvent.VK_RIGHT) this.starGoalX = 0;
if(e.getKeyCode() == KeyEvent.VK_UP
|| e.getKeyCode() == KeyEvent.VK_DOWN) this.starGoalY = 0;
keyDownMap.remove(e.getKeyCode());
}
}
Star.java
package asteroids;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.util.HashMap;
import java.util.Random;
public class Star {
int width, height;
int posx, posy;
float velX, velY, velGoalX, velGoalY;
/** CONSTRUCTOR **/
public Star(int x, int y) {
int rand = new Random().nextInt(Config.STAR_SIZES.length);
width = Config.STAR_SIZES[rand];
height = Config.STAR_SIZES[rand];
posx = x;
posy = y;
}
public void update() {
// pass
}
}
Ship.java
package asteroids;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import javax.swing.ImageIcon;
public class Ship {
public int posx, posy;
public int width, height;
private Image image;
public Ship(int w, int h, String img) {
this.posx = Config.WINDOW_WH[0]/2;
this.posy = Config.WINDOW_WH[1]/2;
this.width = w;
this.height = h;
this.image = new ImageIcon(getClass().getResource("/"+img)).getImage();
}
public Image getImage() {
return this.image;
}
public void setPosx(int x) {posx = x;}
public void setPosy(int y) {posy = y;}
public void setImg(Image img) {
this.image = img;
}
public void update(HashMap keyDownMap) {
// pass
}
}
Config.java
package asteroids;
import java.awt.Color;
public class Config {
// MAIN CANVAS SETTINGS
public static int[] WINDOW_WH = {500, 500};
public static String WINDOW_BG_IMG = "";
public static Color WINDOW_BG_CLR = new Color(40, 42, 45);
// OBJECT SETTINGS
public static int[] STAR_SIZES = {10,5,8,3,7};
public static float lerpSpeed = 0.8f;
}

Jumping square. thread. Prevent from jumping several times

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.

Sprite custom class not working properly, why?

As you will see in the code, I've tried to make a custom sprite class, but for some reason, the values of the variables "disappear" , and if (as you will see) isSprite is true, then even the mainframe won't appear/won't be visible, and it will just run in the background until you stop it manually.
Here is the code of the class:
package testowhat;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Sprite extends Component {
Sprite(String image1) throws IOException, InterruptedException{
playerConstructor(image1);
}
Integer imgPosX; Integer imgPosY;
Integer divideSize2; Integer divideSize1;
Integer Height; Integer Width;
Integer numberOfSpriteCells, numberOfSpriteLayers, numberOfCellsInALine, heightOfCells, widthOfCells, countingNumber1, countingNumber2;
BufferedImage picture;
Boolean isSprite;
String image;
JPanel picturePanel = new JPanel() {
public void paint(Graphics g) {
g.drawImage(picture.getScaledInstance(picture.getWidth()/divideSize1, picture.getHeight()/divideSize2, Image.SCALE_DEFAULT), imgPosX, imgPosY, null);
}
};
private void playerConstructor(String image) throws IOException, InterruptedException {
try {
picture = ImageIO.read(new File(image));
} catch (IOException ex) {System.out.println("File is missing.");}
//----------------------------------------------------------------------
Height = picture.getHeight()+10;
Width = picture.getWidth()+10;
//----------------------------------------------------------------------
picturePanel.setLocation(this.getLocation());
picturePanel.setSize(this.getHeight(), this.getWidth());
//----------------------------------------------------------------------
picturePanel.setMinimumSize(new Dimension(Height, Width));
picturePanel.setMaximumSize(new Dimension(Height, Width));
//----------------------------------------------------------------------
if (this.isVisible() == true) {
picturePanel.setVisible(true);
}
//----------------------------------------------------------------------
this.countingNumber1 = 0;
checkThem();
justDoIt();
}
//--------------------------------------------------------------------------
private void checkThem() {
if (isSprite == null) {
isSprite = false;
}
if (imgPosX == null) {
imgPosX = 0;
imgPosY = 0;
}
if (imgPosY == null) {
imgPosX = 0;
imgPosY = 0;
}
if (numberOfSpriteCells == null) {
numberOfSpriteCells = 6;
}
if (widthOfCells == null) {
widthOfCells = 103;
}
if (heightOfCells == null) {
heightOfCells = 89;
}
if (numberOfSpriteLayers == null) {
numberOfSpriteLayers = 2;
}
}
//--------------------------------------------------------------------------
private void justDoIt() throws InterruptedException {
if (isSprite == true) {
for (countingNumber2=1; countingNumber2<7; countingNumber2++) {
doChange();
Thread.sleep(100);
this.repaint();
this.picturePanel.repaint();
if (countingNumber2 <= 7) {
countingNumber2 = 1;
}
}
}
}
//--------------------------------------------------------------------------
private void doChange() {
imgPosX = imgPosX - widthOfCells;
countingNumber1 = countingNumber1++;
repaint();
picturePanel.repaint();
if (countingNumber1==numberOfSpriteCells/numberOfSpriteLayers) {
imgPosY = imgPosY - heightOfCells;
imgPosX = 0;
}
if (countingNumber1 == numberOfSpriteCells) {
countingNumber1 = 0;
imgPosX = 0;
imgPosY = 0;
repaint();
picturePanel.repaint();
}
}
}
As a sidenote:
I. In the first "version" of the code the doChange() procedure was in
another class.
II. The setbounds of the picture, and the picturepanel are declared in
another class, but is connected.
III. For some reason most of the set variables seem to lose their
values
IV. I've already had a nullPointerException problem with inserting the
doChange() procedure, so I'm guessing that maybe that's the one which
causes these problems.
The results of running the program:
If the isSprite is set to false then:
It runs smoothly and displays the part of the picture we (I) wanted.
and if it is set to true:
Nothing happens, it runs, but nothing will appear, it is just not working correctly.

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