Using this code I would like to add a button to the page that displays when the gamestate is either Dead or Win. This button will let the user either start over or go on to the next level. My action listener is not yet fully coded because I can't even get the button to be visible on the page. I have tried coding in a button using
setLayout(new FlowLayout());
this.add(sOver);
sOver = new Button("Start Over");
sOver.addActionListener(this);
But that results in a an error when the game changes state.
package androidGame;
import java.applet.Applet;
import java.awt.event.*;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.net.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import androidGame.framework.Animation;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class StartingClass extends Applet implements Runnable, KeyListener, ActionListener {
enum GameState {
Running, Dead, Win
}
GameState state = GameState.Running;
private static Robot robot;
public static Heliboy hb, hb2, hb3, hb4, hb5, hb6, hb7, hb8, hb9, hb10, hb11, hb12, hb13, hb14, hb15, hb16;
public static int score = 0;
public static int rHealth = 120;
private Font font = new Font(null, Font.BOLD, 30);
private Image image, currentSprite, character, character2, character3,
characterDown, characterJumped, background, heliboy, heliboy2,
heliboy3, heliboy4, heliboy5;
public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
tilegrassRight, tiledirt, tilefire, tiledoor;
private Graphics second;
private URL base;
private static Background bg1, bg2;
private Animation anim, hanim;
int level = 1;
AudioClip clip;
Button next, sOver;
private ArrayList<Tile> tilearray = new ArrayList<Tile>();
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Robot Mania");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "data/character.png");
character2 = getImage(base, "data/character2.png");
character3 = getImage(base, "data/character3.png");
characterDown = getImage(base, "data/down.png");
characterJumped = getImage(base, "data/jumped.png");
heliboy = getImage(base, "data/heliboy.png");
heliboy2 = getImage(base, "data/heliboy2.png");
heliboy3 = getImage(base, "data/heliboy3.png");
heliboy4 = getImage(base, "data/heliboy4.png");
heliboy5 = getImage(base, "data/heliboy5.png");
background = getImage(base, "data/spacebackground.png");
tiledirt = getImage(base, "data/tiledirt.png");
tilegrassTop = getImage(base, "data/tilegrasstop.png");
tilegrassBot = getImage(base, "data/tilegrassbot.png");
tilegrassLeft = getImage(base, "data/tilegrassleft.png");
tilegrassRight = getImage(base, "data/tilegrassright.png");
tilefire = getImage(base, "data/tilefire.png");
tiledoor = getImage(base, "data/tiledoor.png");
anim = new Animation();
anim.addFrame(character, 1250);
anim.addFrame(character2, 50);
anim.addFrame(character3, 50);
anim.addFrame(character2, 50);
hanim = new Animation();
hanim.addFrame(heliboy, 100);
hanim.addFrame(heliboy2, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy5, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy2, 100);
currentSprite = anim.getImage();
}
#Override
public void start() {
//Sound.MAIN.loop();
bg1 = new Background(0, 0);
bg2 = new Background(2160, 0);
robot = new Robot();
// Initialize Tiles
try {
loadMap("data/map"+ level +".txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random random = new Random();
int randomInt = random.nextInt(500);
hb = new Heliboy(700, 360);
hb2 = new Heliboy(900 + randomInt, 360);
hb3 = new Heliboy(2300 + randomInt, 360);
hb4 = new Heliboy(2900 + randomInt, 360);
hb5 = new Heliboy(3400 + randomInt, 360);
hb6 = new Heliboy(3900 + randomInt, 360);
hb7 = new Heliboy(4300 + randomInt, 360);
hb8 = new Heliboy(4700 + randomInt, 360);
hb9 = new Heliboy(5000 + randomInt, 360);
hb10 = new Heliboy(5300 + randomInt, 360);
hb11 = new Heliboy(5700 + randomInt, 360);
hb12 = new Heliboy(6000 + randomInt, 360);
hb13 = new Heliboy(6300 + randomInt, 360);
hb14 = new Heliboy(6700 + randomInt, 360);
hb15 = new Heliboy(7000 + randomInt, 360);
hb16 = new Heliboy(7200 + randomInt, 360);
Thread thread = new Thread(this);
thread.start();
}
private void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
int width = 0;
int height = 0;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (true) {
String line = reader.readLine();
// no more lines to read
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();
for (int j = 0; j < 12; j++) {
String line = (String) lines.get(j);
for (int i = 0; i < width; i++) {
if (i < line.length()) {
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tilearray.add(t);
}
}
}
}
#Override
public void run() {
if (state == GameState.Running) {
while (true) {
robot.update();
if (robot.isJumped()) {
currentSprite = characterJumped;
} else if (robot.isJumped() == false
&& robot.isDucked() == false) {
currentSprite = anim.getImage();
}
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
if (p.isVisible() == true) {
p.update();
} else {
projectiles.remove(i);
}
}
updateTiles();
hb.update();
hb2.update();
hb3.update();
hb4.update();
hb5.update();
hb6.update();
hb7.update();
hb8.update();
hb9.update();
hb10.update();
hb11.update();
hb12.update();
hb13.update();
hb14.update();
hb15.update();
hb16.update();
bg1.update();
bg2.update();
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (rHealth == 0) {
state = GameState.Dead;
Sound.MAIN.stop();
//Sound.DIE.play();
sOver = new Button("Start Over");
this.add(sOver);
sOver.addActionListener(this);
sOver.setVisible(true);
revalidate();
repaint();
}
if (robot.getCenterY() > 500) {
state = GameState.Dead;
Sound.MAIN.stop();
//Sound.DIE.play();
sOver = new Button("Start Over");
this.add(sOver);
sOver.addActionListener(this);
sOver.setVisible(true);
revalidate();
repaint();
}
if (score == 5){
state = GameState.Win;
Sound.MAIN.stop();
//Sound.WIN.play();
next = new Button("Next Level");
this.add(next);
next.addActionListener(this);
next.setVisible(true);
revalidate();
repaint();
}
}
}
}
public void animate() {
anim.update(10);
hanim.update(50);
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
if (state == GameState.Running) {
g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
paintTiles(g);
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
g.setColor(Color.BLUE);
g.fillRect(p.getX(), p.getY(), 10, 5);
}
g.drawImage(currentSprite, robot.getCenterX() - 61,
robot.getCenterY() - 63, this);
g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
hb.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
hb2.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb3.getCenterX() - 48,
hb3.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb4.getCenterX() - 48,
hb4.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb5.getCenterX() - 48,
hb5.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb6.getCenterX() - 48,
hb6.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb7.getCenterX() - 48,
hb7.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb8.getCenterX() - 48,
hb8.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb9.getCenterX() - 48,
hb9.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb10.getCenterX() - 48,
hb10.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb11.getCenterX() - 48,
hb11.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb12.getCenterX() - 48,
hb12.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb13.getCenterX() - 48,
hb13.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb14.getCenterX() - 48,
hb14.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb15.getCenterX() - 48,
hb15.getCenterY() - 48, this);
g.drawImage(hanim.getImage(), hb16.getCenterX() - 48,
hb16.getCenterY() - 48, this);
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString("Health: " + Integer.toString(rHealth), 5, 30);
g.drawString("Score: " + Integer.toString(score), 650, 30);
} else if (state == GameState.Dead) {
//setLayout(new FlowLayout());
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString("You're Dead!", 300, 200);
g.drawString("Score: " + score, 300, 250);
}
else if (state == GameState.Win) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString("You Beat this level!", 300, 200);
g.drawString("Score: " + score, 300, 250);
level++;
}
}
private void updateTiles() {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
t.update();
}
}
private void paintTiles(Graphics g) {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
currentSprite = characterDown;
if (robot.isJumped() == false) {
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
robot.jump();
break;
case KeyEvent.VK_CONTROL:
if (robot.isDucked() == false && robot.isJumped() == false
&& robot.isReadyToFire()) {
robot.shoot();
robot.setReadyToFire(false);
}
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
currentSprite = anim.getImage();
robot.setDucked(false);
break;
case KeyEvent.VK_LEFT:
robot.stopLeft();
break;
case KeyEvent.VK_RIGHT:
robot.stopRight();
break;
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_CONTROL:
robot.setReadyToFire(true);
Sound.GUN.play();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static Background getBg1() {
return bg1;
}
public static Background getBg2() {
return bg2;
}
public static Robot getRobot() {
return robot;
}
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == next)
level ++;
{
}
if (evt.getSource() == sOver)
level = 1;
{
}
}
}
The error message that I was getting is:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at androidGame.StartingClass.paint(StartingClass.java:372)
at androidGame.StartingClass.update(StartingClass.java:305)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$300(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
this.add(sOver);
sOver = new Button("Start Over");
I guess the error is here. You gotta initialize sOver before adding it to the applet. So put it like this :
sOver = new Button("Start Over");
this.add(sOver);
Let's see whether it works or not.
Related
So I'm making a game where you jump on rocks and you must not jump on rock which is covered by water. I'm stuck at the part where rocks (circles) randomly disappear in water and randomly appear and around 1.5 seconds before they disappear make it change color. I think its best to use javax.swing.Timer.
Could you help me achieve that?
Here is my code so far:
Main class:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferStrategy;
import java.util.Random;
import javax.swing.Timer;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = -7800496711589684767L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Random r;
private Handler handler;
//private HUD hud;
private Menu menu;
public enum STATE {
Menu,
Help,
Game
};
public STATE gameState = STATE.Menu;
public Game() {
handler = new Handler();
menu = new Menu(this, handler);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "My game", this);
//hud = new HUD();
r = new Random();
//if(gameState == STATE.Game) {
if(gameState == STATE.Game) { //handler.addObject(new Player(100, 200, ID.Player));
}
//handler.addObject(new Player(100, 200, ID.Player));
//handler.addObject(new BasicEnemy(100, 200, ID.BasicEnemy));
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try {
thread.join();
running = false;
}catch(Exception ex) { ex.printStackTrace(); }
}
public void run()
{
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
//System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick() {
handler.tick();
//hud.tick();
if(gameState == STATE.Game) {
Random r = new Random();
long now = System.currentTimeMillis();
int b = 0;
//System.out.println(now);
long extraSeconds = 500;
}else if(gameState == STATE.Menu) {
menu.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
long now = System.currentTimeMillis();
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, WIDTH, HEIGHT);
if(gameState == STATE.Game) {
g.setColor(new Color(209, 155, 29));
for(int i = 0; i < 5; i++) {
g.fillOval(80 + (100 * i), 325, 70, 20);
}
if(gameState == STATE.Game) {
}else if(gameState == STATE.Menu || gameState == STATE.Help){
menu.render(g);
}
handler.render(g);
if(gameState == STATE.Game) {
}
//hud.render(g);
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max) {
if(var >= max)
return var = max;
else if(var <= max)
return var = min;
else
return var;
}
public static void main(String[] args) {
new Game();
}
}
GameObject class:
package com.pitcher654.main;
import java.awt.Graphics;
public abstract class GameObject {
protected static int x, y;
protected ID id;
protected int velX, velY;
public GameObject(int x, int y, ID id) {
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick();
public abstract void render(Graphics g);
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setID(ID id) {
this.id = id;
}
public ID getID() {
return id;
}
public void setVelX(int velX) {
this.velX = velX;
}
public void setVelY(int velY) {
this.velY = velY;
}
public int getVelX() {
return velX;
}
public int getVelY() {
return velY;
}
}
Handler class:
package com.pitcher654.main;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler {
LinkedList<GameObject> object = new LinkedList<GameObject>();
public void tick() {
for(int i = 0; i < object.size(); i++) {
GameObject tempObject = object.get( i );
tempObject.tick();
}
}
public void render(Graphics g) {
for(int i = 0; i < object.size(); i++) {
GameObject tempObject = object.get(i);
tempObject.render(g);
}
}
public void addObject(GameObject object) {
this.object.add(object);
}
public void removeObject(GameObject object) {
this.object.remove(object);
}
}
ID class:
package com.pitcher654.main;
public enum ID {
Player(),
Player2(),
BasicEnemy(),
Misc();
}
KeyInput class:
package com.pitcher654.main;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyInput extends KeyAdapter{
private Handler handler;
public KeyInput(Handler handler) {
this.handler = handler;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
for(int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player) {
//kez events for Player 1
//GameObject object = new GameObject(0, 0, ID.Misc);
//System.out.println(tempObject.getID());
if(GameObject.x != 500) {
if(key == KeyEvent.VK_RIGHT) {
Player.currentStone++;
tempObject.setX(tempObject.getX() + 100);
}
}
if(GameObject.x != 100){
if(key == KeyEvent.VK_LEFT) {
Player.currentStone--;
tempObject.setX(tempObject.getX() - 100);
}
}
}
}
if(key == KeyEvent.VK_ESCAPE) System.exit(1);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
}
}
Menu class:
package com.pitcher654.main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.pitcher654.main.Game.STATE;
public class Menu extends MouseAdapter{
private Game game;
private Handler handler;
private GameObject Player;
public Menu(Game game, Handler handler) {
this.game = game;
this.handler = handler;
}
public void mouseClicked(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(game.gameState == STATE.Menu) {
//play 1 button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 150, 250, 64)) {
game.gameState = STATE.Game;
handler.addObject(new Player(100, 200, ID.Player));
//handler.addObject(new BasicEnemy(0, 0, ID.BasicEnemy));
}
//Instructions button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 250, 250, 64)) {
game.gameState = STATE.Help;
}
//Quit button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 350, 250, 64)) {
System.exit(1);
}
}
//Bacl to menu in game button
if(game.gameState == STATE.Help) {
if(mouseOver(mx, my, 23, 395, 100, 32)) {
game.gameState = STATE.Menu;
//handler.object.remove(Player);
}
}
}
public void mouseReleased(MouseEvent e) {
}
private boolean mouseOver(int mx, int my, int x, int y, int width, int height) {
if(mx > x && mx < x + width) {
if(my > y && my < y + height) {
return true;
}else return false;
}else return false;
}
public void tick() {
}
public void render(Graphics g) {
if(game.gameState == STATE.Menu) {
Font fnt = new Font("Trebuchet MS", 30, 15);
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, game.WIDTH, game.HEIGHT);
g.setColor(Color.white);
g.setFont(new Font("Papyrus", 1, 50));
g.drawString("Price iz davnine", (Game.WIDTH - 250) / 2 - 50, 70);
g.drawRect((Game.WIDTH - 250) / 2, 150, 250, 64);
g.drawRect((Game.WIDTH - 250) / 2, 250, 250, 64);
g.drawRect((Game.WIDTH - 250) / 2, 350, 250, 64);
g.setFont(new Font("Trebuchet MS", 5000, 20));
g.drawString("Play", (Game.WIDTH - 250) / 2 + 110, 190);
g.setFont(fnt);
g.drawString("How to Play", (Game.WIDTH - 250) / 2 + 85, 290);
g.drawString("Quit", (Game.WIDTH - 250) / 2 + 105, 390);
}else if(game.gameState == STATE.Help) {
g.setColor(Color.white);
g.setFont(new Font("Papyrus", 1, 50));
g.drawString("How to play", (Game.WIDTH - 250) / 2 - 50, 70);
g.setFont(new Font("Trebuchetr MS", 30, 10));
g.drawRect(23, 395, 100, 32);
g.setColor(Color.black);
g.drawString("Back to Menu", 33, 415);
}
}
}
Player class:
package com.pitcher654.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Timer;
import com.pitcher654.main.Game.STATE;
public class Player extends GameObject {
Random r = new Random();
public static int currentStone = 1;
public Player(int x, int y, ID id) {
super(x, y, id);
//velX = r.nextInt(5) + 1;
//velY = r.nextInt(5);
}
public void tick() {
x += velX;
y += velY;
//System.out.println(x);
//if(x == 500) x = 500;
}
public void render(Graphics g) {
if(id == ID.Player) g.setColor(Color.white);
g.fillRect(x, y, 32, 32);
g.drawLine(x + 15, y, x + 15, y + 100);
g.drawLine(x + 15, y + 100, x, y + 135);
g.drawLine(x + 15, y + 100, x + 33, y + 135);
g.drawLine(x + 15, y + 70, x - 35, y + 30);
g.drawLine(x + 15, y + 70, x + 65, y + 30);
/*if(game.gameState == STATE.Menu) {
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
}*/
}
}
And window class:
package com.pitcher654.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends Canvas{
private static final long serialVersionUID = 9086330915853125521L;
BufferedImage image = null;
URL url = null;
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
try {
image = ImageIO.read(new URL("https://static.wixstatic.com/media/95c249_b887de2536aa48cb962e2336919d2693.png/v1/fill/w_600,h_480,al_c,usm_0.66_1.00_0.01/95c249_b887de2536aa48cb962e2336919d2693.png"));
} catch (IOException e) {
e.printStackTrace();
}
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setIconImage(image);
//DrawingPanel panel = new DrawingPanel();
//frame.getContentPane().add(panel);
frame.setVisible(true);
frame.requestFocus();
game.start();
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -7662876024842980779L;
public void paintComponent(Graphics g) {
g.setColor(new Color(209, 155, 29));
g.fillOval(100, 100, 100, 100);
}
}
}
Based on you code, a Swing Timer isn't what you want. You already have a "game/main" loop which should be updating the current state of the game on each cycle and rendering it, you simply need to devise a means by which you can create a "rock", with a given life span, each time it's rendered, it needs to check if it's life span is nearly over and have it removed when it dies.
The rock is really just another entity in your game, which can be updated and rendered.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RockyRoad {
public static void main(String[] args) {
new RockyRoad();
}
public RockyRoad() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class Game extends Canvas implements Runnable {
private static final long serialVersionUID = -7800496711589684767L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Random rnd;
private List<Entity> entities = new ArrayList<>(25);
public enum STATE {
Menu,
Help,
Game
};
public STATE gameState = STATE.Game;
public Game() {
rnd = new Random();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
start();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try {
thread.join();
running = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if (running) {
update();
render();
}
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
//System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick() {
//hud.tick();
}
protected void update() {
if (gameState == STATE.Game) {
if (rnd.nextBoolean()) {
System.out.println("New...");
int x = rnd.nextInt(getWidth() - Rock.SIZE);
int y = rnd.nextInt(getHeight() - Rock.SIZE);
int lifeSpan = 4000 + rnd.nextInt(6000);
entities.add(new Rock(lifeSpan, x, y));
}
List<Entity> toRemove = new ArrayList<>(entities.size());
List<Entity> control = Collections.unmodifiableList(entities);
for (Entity entity : entities) {
if (entity.update(control, this) == EntityAction.REMOVE) {
System.out.println("Die...");
toRemove.add(entity);
}
}
entities.removeAll(toRemove);
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
long now = System.currentTimeMillis();
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, WIDTH, HEIGHT);
if (gameState == STATE.Game) {
g.setColor(new Color(209, 155, 29));
if (gameState == STATE.Game) {
for (Entity entity : entities) {
entity.render(g, this);
}
}
g.dispose();
bs.show();
}
}
public static int clamp(int var, int min, int max) {
if (var >= max) {
return var = max;
} else if (var <= max) {
return var = min;
} else {
return var;
}
}
}
public interface Renderable {
public void render(Graphics2D g2d, Component parent);
}
public enum EntityAction {
NONE,
REMOVE;
}
public interface Entity extends Renderable {
// In theory, you'd pass the game model which would determine
// all the information the entity really needed
public EntityAction update(List<Entity> entities, Component parent);
}
public static class Rock implements Renderable, Entity {
protected static final int SIZE = 20;
private int lifeSpan;
private long birthTime;
private int x, y;
public Rock(int lifeSpan, int x, int y) {
if (lifeSpan <= 1500) {
throw new IllegalArgumentException("Life span for a rock can not be less then or equal to 1.5 seconds");
}
this.lifeSpan = lifeSpan;
birthTime = System.currentTimeMillis();
this.x = x;
this.y = y;
}
#Override
public void render(Graphics2D g2d, Component parent) {
long age = System.currentTimeMillis() - birthTime;
if (age < lifeSpan) {
if (age < lifeSpan - 1500) {
g2d.setColor(Color.BLUE);
} else {
g2d.setColor(Color.RED);
}
g2d.fillOval(x, y, SIZE, SIZE);
}
}
#Override
public EntityAction update(List<Entity> entities, Component parent) {
EntityAction action = EntityAction.NONE;
long age = System.currentTimeMillis() - birthTime;
System.out.println("Age = " + age + "; lifeSpan = " + lifeSpan);
if (age >= lifeSpan) {
action = EntityAction.REMOVE;
}
return action;
}
}
}
I wanted to export my game into a .jar file. It exported; when I ran it the frame came up, but the panel didn't load. I have my frame and panel in two different class files but I didn't think that made a difference. Also, It completely works in Eclipse. I exported my .jar file under Runnable Jar File and packaged required libraries into generated jar. In the SlashRunnerPanel I imported and resized many images. Can that be the problem?
Here is my code for the frame:
package baseFiles;
import javax.swing.*;
public class SlashRunnerFrame {
public static void main(String args[]) {
JFrame frame = new JFrame(); // Create new JFrame (the window)
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
SlashRunnerPanel panel = new SlashRunnerPanel();
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
panel.mainLoop();
}
}
Here is my code for the panel:
package baseFiles;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.imageio.*;
import java.io.File;
import player.Player;
import surroundings.Obstacle;
public class SlashRunnerPanel extends JPanel implements KeyListener,
ActionListener, MouseListener
{
public static boolean mailbox1 = false;
Color skin = new Color(255, 223, 196);
boolean goo = true;
BufferedImage origMailBox;
BufferedImage house;
BufferedImage ReplaceableBackgroundPic;
BufferedImage origPlayerBack;
BufferedImage origPlayerFront;
BufferedImage origletter;
BufferedImage blackScreen;
BufferedImage exclamation;
BufferedImage borderRocks;
BufferedImage pause;
Image ReplaceableBackground;
Image resizedHouse;
Image mailbox;
Image PlayerBack;
Image PlayerFront;
Image letter;
Image Exclamation;
ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>();
Obstacle mailboxRegion;
Player player;
Obstacle Beginning;
String ps = System.getProperty("file.separator");
//Animation for walking
boolean aniUp = true;
boolean aniDown;
boolean aniRight;
boolean aniLeft;
boolean lastAni;
//mail
boolean openMail = false;
boolean isMailbox;
boolean mailcontinue;
boolean arrow = true;
boolean showMailRegion;
//Scene
boolean begin = true;
int cmX;
int cmY;
boolean obstaclesInBeginning = true;
boolean showObstInBegin;
//Keys
boolean showObstacles;
boolean stats;
boolean pausebool;
boolean play = true;
public SlashRunnerPanel()
{
try{
borderRocks = ImageIO.read(new File("src" + ps + "Images" + ps + "Boundary.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
exclamation = ImageIO.read(new File("src" + ps + "Images" + ps + "Exclamation.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
origletter = ImageIO.read(new File("src" + ps + "Images" + ps + "Scroll.png"));
} catch(Exception e) {System.out.println(e.getMessage());}
try{
blackScreen = ImageIO.read(new File("src" + ps + "Images" + ps + "BlackScreen.png"));
} catch(Exception e) {e.printStackTrace();}
try{
house = ImageIO.read(new File("src" + ps + "Images" + ps + "House.png"));
} catch(Exception e) {e.printStackTrace();}
try{
ReplaceableBackgroundPic = ImageIO.read(new File("src" + ps + "Images" + ps + "ReplaceableBackground.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origMailBox = ImageIO.read(new File("src" + ps + "Images" + ps + "SmallMailbox.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origPlayerBack = ImageIO.read(new File("src" + ps + "Images" + ps + "WarriorBack.png"));
} catch(Exception e) {e.printStackTrace();}
try{
origPlayerFront = ImageIO.read(new File("src" + ps + "Images" + ps + "WarriorFront.png"));
} catch(Exception e) {e.printStackTrace();}
try{
pause = ImageIO.read(new File("src" + ps + "Images" + ps + "Pause.png"));
} catch(Exception e) {e.printStackTrace();}
}
public void mainLoop()
{
obstacles.add(new Obstacle(140, 170, 300, 545));
obstacles.add(new Obstacle(560, 170, 350, 500));
obstacles.add(new Obstacle(500, 900, 800, 100));
this.setFocusable(true);
addKeyListener(this);
addMouseListener(this);
Exclamation = exclamation.getScaledInstance(20, 20, Image.SCALE_FAST);
letter = origletter.getScaledInstance(500, 500, Image.SCALE_FAST);
ReplaceableBackground = ReplaceableBackgroundPic.getScaledInstance(1600, 2336, Image.SCALE_FAST);
resizedHouse = house.getScaledInstance((int) (getWidth() / 5), (int) (getHeight() / 4), Image.SCALE_FAST);
mailbox = origMailBox.getScaledInstance((int)(getWidth() / 6), (int) (getHeight() / 6), Image.SCALE_FAST);
Image PlayerBack = origPlayerBack.getScaledInstance((int)(getWidth() / 30), (int) (getHeight() / 12), Image.SCALE_FAST);
Image PlayerFront = origPlayerFront.getScaledInstance((int)(getWidth() / 30), (int) (getHeight() / 12), Image.SCALE_FAST);
player = new Player(585, 725, (int)(getWidth() / 30), (int) (getHeight() / 12), false, PlayerFront, PlayerBack);
mailboxRegion = new Obstacle(795, 750, 50, 50);
Beginning = new Obstacle(450, 750, 100, 100);
while(goo)
{
if(player.intersects(Beginning) && obstaclesInBeginning)
player.playerX += 10;
if(!player.dead)
player.move(obstacles);
updateCamera();
if(player.experience == 100)
{
player.experience = 0;
player.experienceLv++;
}
checkCondition();
repaint();
wait(100);
}
}
public void wait(int milsec)
{
try{
Thread.sleep(milsec);
} catch(Exception e) {System.out.println(e.getMessage());}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(begin && !pausebool && play) //For beginning
{
g.drawImage(ReplaceableBackground, 150 - cmX, -620 - cmY, null);
g.drawImage(resizedHouse, 600 - cmX, 563 - cmY, null);
g.drawImage(mailbox, 720 - cmX, 670 - cmY, null);
g.drawImage(pause, 900, 10, null);
if(obstaclesInBeginning)
g.drawImage(borderRocks,523 - cmX,755 - cmY,null);
}
if(pausebool)
{
g.drawRect(0, 0, 1000, 1000);
}
if(arrow )
{
g.drawImage(Exclamation, 790 - cmX, 665 - cmY, null);
}
player.drawTo(g, 500, 450);
if(isMailbox)
{
g.setColor(Color.magenta);
g.setFont(new Font("AlgerianBasD", Font.BOLD, 15));
g.drawString("Press 'Q' to open the mailbox!", 600, 300);
}
if(showObstInBegin)
{
obstBegin(g);
}
if(play)
{
g.setColor(Color.black);
g.fillRect(738, 35, 250, 30);
g.fillRect(738, 90, 250, 30);
g.setColor(Color.red);
g.fillRect(738, 35, (int)(player.playerHealth * 2.5), 30);
g.setFont(new Font("AlgerianBasD", Font.BOLD, 20));
g.drawString("Health:", 738, 30);
g.setColor(new Color(128, 255, 210));
g.drawString("Experience:", 738, 85);
g.fillRect(738, 90, (int)(player.experience * 2.5), 30);
g.setColor(new Color(10, 133, 255));
g.drawString("" + player.experienceLv, 850, 110);
}
if(showObstacles)
{
drawObst(g, obstacles);
}
if(showMailRegion)
{
drawMailRegion(g);
}
if(stats)
{
g.setColor(Color.yellow);
g.drawRect(1, 600, 200, 300);
g.setFont(new Font("AlgerianBasD", Font.PLAIN, 15));
g.setColor(Color.black);
g.drawString("Stats:", 50, 620);
g.setColor(new Color(140, 0, 0));
g.drawString("Overall Strength: " + player.completeStrength, 3, 650);
g.setColor(new Color(100, 88, 115));
g.drawString("Armor: " + player.playerArmor, 3, 680);
g.setColor(Color.yellow);
g.drawString("X: " + player.playerX, 3, 710);
g.drawString("Y: " + player.playerY, 3, 740);
}
if(openMail && !mailcontinue)
{
g.drawImage(blackScreen,0, 0, null);
g.drawImage(letter, 250, 200, null);
}
}
public void checkCondition()
{
if(player.intersects(mailboxRegion))
{
isMailbox = true;
} if( isMailbox && !player.intersects(mailboxRegion))
{
isMailbox = false;
}
}
public void drawObst(Graphics g, ArrayList<Obstacle> obst)
{
for(int i = 0; i < obst.size(); i++)
{
g.setColor(Color.magenta);
g.fillRect(obst.get(i).getX() - cmX, obst.get(i).getY() - cmY, obst.get(i).getWidth(), obst.get(i).getHeight());
}
}
public void drawMailRegion(Graphics g)
{
g.setColor(Color.cyan);
g.fillRect(mailboxRegion.getX() - cmX, mailboxRegion.getY() - cmY, mailboxRegion.getWidth(), mailboxRegion.getHeight());
}
public void obstBegin(Graphics g)
{
g.setColor(Color.ORANGE);
g.fillRect(Beginning.getX() - cmX, Beginning.getY() - cmY, Beginning.getWidth(), Beginning.getHeight());
}
public void updateCamera()
{
cmX = player.playerX - getWidth() / 2;
cmY = player.playerY - getHeight() / 2;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_L)
{
if(stats == true)
{
stats = false;
} else
stats = true;
}
if(isMailbox && !openMail && key == KeyEvent.VK_Q)
{
openMail = true;
isMailbox = false;
arrow = false;
obstaclesInBeginning = false;
}
else if(openMail && key == KeyEvent.VK_Q)
{
obstaclesInBeginning = false;
openMail = false;
repaint();
}
if(key == KeyEvent.VK_EQUALS)
{
if(pausebool)
pausebool = false;
else
pausebool = true;
}
if(key == KeyEvent.VK_BACK_SLASH)
{
if(showObstacles == true)
{
showMailRegion = false;
showObstacles = false;
showObstInBegin = false;
} else {
showObstacles = true;
showMailRegion = true;
showObstInBegin = true;
}
}
if(key == KeyEvent.VK_W)
{
player.up = true;
player.aniUp = true;
player.aniDown = false;
player.aniRight = false;
player.aniLeft = false;
}
if(key == KeyEvent.VK_S)
{
player.down = true;
player.aniDown = true;
player.aniUp = false;
player.aniRight = false;
player.aniLeft = false;
}
if(key == KeyEvent.VK_A)
{
player.left = true;
}
if(key == KeyEvent.VK_D)
{
player.right = true;
}
repaint();
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_W)
{
player.up = false;
}
if(key == KeyEvent.VK_S)
{
player.down = false;
}
if(key == KeyEvent.VK_A)
{
player.left = false;
}
if(key == KeyEvent.VK_D)
{
player.right = false;
}
}
public void keyTyped(KeyEvent e)
{
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
}
}
Try running the game on the Event Dispatch Thread. Swing is not thread safe; if you try to create and modify controls off of the Event Dispatch Thread than things may not work as you expect; controls not displaying is a very common result.
EventQueue.invokeLater is the most common way to make tasks run on the EDT, as seen here:
package baseFiles;
import javax.swing.*;
public class SlashRunnerFrame
{
public static void main(String args [])
{
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(); // Create new JFrame (the window)
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
SlashRunnerPanel panel = new SlashRunnerPanel();
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
panel.mainLoop();
}
});
}
}
If this doesn't fix your problem, then your issue is almost certainly in the code of SlashRunnerPanel, not this code.
Try setting a panel.setPreferredSize(new Dimension(someHeight, someWidth)) and after that frame.pack()
EDIT:
Try this:
package baseFiles;
import javax.swing.*;
import java.awt.Dimension;
public class SlashRunnerFrame {
JFrame frame = new JFrame();
SlashRunnerPanel panel = new SlashRunnerPanel();
public SlashRunnerFrame(){
// Create new JFrame (the window)
panel.mainLoop();
panel.setPreferredSize(new Dimension(1000, 800));
frame.setSize(1000, 800); // Set it to 1000x800 pixels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Quit on red X
frame.setResizable(false); // Disallow resizing of window
// Change this line if you want to use a different panel
frame.add(panel); // Staple the panel to the JFrame
frame.setVisible(true); // So we can see our window
frame.pack();
}
public static void main(String args[]) {
new SlashRunnerFrame();
}
}
see if it works
modify your panel before adding it to the frame.
I figured it out. When it was loading in the images in the .jar file it was trying to access the folder on my desktop instead of the one in the jar file. So it sent an error because it was trying to access a file that is out of the .jar file. My solution was to replace:
try{
yourImageVariableName = ImageIO.read(new File("yourImagePath1" + ps + "yourImagePath2" + ps + "yourImage.png"));
} catch(Exception e) {e.printStackTrace();}
with:
try{
yourImageVariableName = ImageIO.read(yourClassName.class.getResourceAsStream("/yourImagePath2/yourImage.png"));
} catch(Exception e) {e.printStackTrace();}
I'm trying to launch a Game launcher and it was working fine until yesterday (I had most of the code written already) and then it just starts throwing Illegal state exceptions all over the place like theres no tomorrow.
And I for the life of me cannot figure out the solution :(
So this is my code:
package com.MHafi.Pandora.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import com.MHafi.Pandora.Configuration;
import com.MHafi.Pandora.Display;
import com.MHafi.Pandora.RunGame;
import com.MHafi.Pandora.input.InputHandler;
public class Launcher extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private JFrame frame = new JFrame();
Configuration config = new Configuration();
private int width = 800;
private int height = 390;
protected int button_width = 80;
protected int button_height = 39;
boolean running = false;
Thread thread;
private BufferedImage img;
public Launcher(int id) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
frame.setUndecorated(true);
frame.setTitle(Display.TITLE + " Launcher");
frame.setSize(new Dimension(width, height));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().add(window);
//frame.add(this);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
window.setLayout(null);
System.out.println("YAY");
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
startMenu();
frame.repaint();
}
public void updateFrame() {
if (InputHandler.dragged) {
Point p = frame.getLocation();
int x = frame.getX();
int y = frame.getY();
frame.setLocation (x + InputHandler.MouseDX - InputHandler.MousePX, y + InputHandler.MouseDY - InputHandler.MousePY);
}
}
public void startMenu() {
running = true;
thread = new Thread(this, "menu");
thread.start();
}
public void stopMenu() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
requestFocus();
while (running) {
renderMenu();
updateFrame();
}
}
private void renderMenu() throws IllegalStateException {
System.out.println("1");
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
System.out.println("2");
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 390);
System.out.println("3");
try {
g.drawImage(ImageIO.read(Launcher.class.getResource("/Launcher.png")), 0, 0, 800, 390, null);
System.out.println("4");
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 110 && InputHandler.MouseY < 110 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/play_on.png")), 50, 110, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 118, 30, 14, null);
if (InputHandler.MouseButton == 1) {
config.loadConfiguration("res/config/config.xml");
dispose();
new RunGame();
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/play_off.png")), 50, 110, 60, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 140 && InputHandler.MouseY < 140 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Options_on.png")), 50, 141, 100, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 155, 149, 30, 14, null);
if (InputHandler.MouseButton == 1) {
System.out.println("Options");
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Options_off.png")), 50, 140, 100, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 175 && InputHandler.MouseY < 175 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Help_on.png")), 50, 175, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 183, 30, 14, null);
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Help_off.png")), 50, 175, 60, 30, null);
}
if (InputHandler.MouseX > 50 && InputHandler.MouseX < 50 + 60 && InputHandler.MouseY > 210 && InputHandler.MouseY < 210 + 25) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Quit_on.png")), 50, 210, 60, 30, null);
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Pointer.png")), 115, 218, 30, 14, null);
if (InputHandler.MouseButton == 1) {
System.exit(0);
}
} else {
g.drawImage(ImageIO.read(Launcher.class.getResource("/menu/Quit_off.png")), 50, 210, 60, 30, null);
}
} catch (IOException e) {
e.printStackTrace();
}
g.dispose();
bs.show();
}
}
And here is the error thrown:
YAY
1
Exception in thread "menu" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.<init>(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Window.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Window.createBufferStrategy(Unknown Source)
So what's going on?
Why can't I create a BufferStrategy?
Well, a problem I see here is this call createBufferStrategy(3) in the renderMenu method. The method createBufferStrategy can cause such exceptions if the JFrame (or to be more general, the Window) wasn't set visible before (or added to a component that is visible) as you can see in the JavaDoc.
I see two ways to fix it:
think about the purpose of private JFrame frame and if you should use this instead, since Launcher is a JFrame itself (you're setting frame as visible, not the Launcher instance)
change this.getBufferStrategy() and createBufferStrategy(3) to frame.getBufferStrategy() and frame.createBufferStrategy(3)
If you used the second idea, then also think about removing JFrame as the parent class for Launcher, because it creates an own JFrame instance, instead of using "himself" as the JFrame.
I've got this GUI that I want to run and when I try to make a Object out of the class I get the error Cannot instantiate the type GUI. So what does it mean and how can I fix?
The code in the mainclass
public static void main(String[] args){
//Classes
GUI go = new GUI();
//Running Class Methods
//JFrame
//JFrame frame = new JFrame("Yatsy");
go.setVisible(true);
go.setVisible(true);
//go.setLocation((dim.width - width) / 2, (dim.height - height) / 2);
go.setSize(width, height);
System.out.println(width + " " + height);
//draw paint = new draw();
//go.add(paint);
}
code inside the GUI class
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
So I wonder why do I get an error?
I'm using java 1.7!
For these who want to know this is the full code!!!!
package Christofer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public abstract class GUI extends JFrame implements MouseListener{
private static final long serialVersionUID = 1L;
int dice1, dice2, dice3, dice4, dice5;
private JButton roll;
private JButton nextPlayer;
private JButton bDice1;
private JButton quit;
private JButton use;
private JPanel panel;
public int rolls = 0;
public boolean turn = true;
public boolean start = true;
boolean saved1 = false, saved2 = false, saved3 = false, saved4 = false, saved5 = false;
int rollResult1;
int rollResult2;
int rollResult3;
int rollResult4;
int rollResult5;
String sRollResult1, sRollResult2, sRollResult3, sRollResult4, sRollResult5;
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
this.setBackground(Color.BLUE);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(getWidth() / 2 - 75, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 1
g2d.fillRoundRect(getWidth() / 2 - 40, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 2
g2d.fillRoundRect(getWidth() / 2 - 5, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 3
g2d.fillRoundRect(getWidth() / 2 + 30, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 4
g2d.fillRoundRect(getWidth() / 2 + 65, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 5
//Score Board
g2d.fillRect(30, 70, 370, getHeight() - 125);
g2d.setColor(Color.BLACK);
g2d.drawLine(150, 70, 150, getHeight() - 30);
g2d.drawLine(30, 70, 400, 70);
g2d.drawString("Ones", 35, 85);
g2d.drawLine(30, 90, 400, 90);
g2d.drawString("Twos", 35, 105);
g2d.drawLine(30, 110, 400, 110);
g2d.drawString("Threes", 35, 125);
g2d.drawLine(30, 130, 400, 130);
g2d.drawString("Fours", 35, 145);
g2d.drawLine(30, 150, 400, 150);
g2d.drawString("Fives", 35, 165);
g2d.drawLine(30, 170, 400, 170);
g2d.drawString("Sixes", 35, 185);
g2d.drawLine(30, 190, 400, 190);
if(start == false){
g.setColor(Color.BLACK);
Font font = new Font("Arial", Font.PLAIN, 25);
g2d.setFont(font);
g2d.drawString( sRollResult1 + " " + sRollResult2 + " " + sRollResult3 + " " + sRollResult4 + " " + sRollResult5, getWidth() / 2 - 70 , getHeight() / 2 - 25 );
if(turn == false){
g2d.setColor(Color.RED);
g2d.drawString("Out Of Rolls", getWidth() / 2 - 70, getHeight() / 2 - 75);
}
}
}
public int roll1(){
if (saved1 == false){
dice1 = (int )(Math.random() * 6 + 1);
}
return dice1;
}
public int roll2(){
if (saved2 == false){
dice2 = (int )(Math.random() * 6 + 1);
}
return dice2;
}
public int roll3(){
if (saved3 == false){
dice3 = (int )(Math.random() * 6 + 1);
}
return dice3;
}
public int roll4(){
if (saved4 == false){
dice4 = (int )(Math.random() * 6 + 1);
}
return dice4;
}
public int roll5(){
if (saved5 == false){
dice5 = (int )(Math.random() * 6 + 1);
}
return dice5;
}
private class Handlerclass implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.println("X: " + mx + " Y: " + my);
if(mx < getWidth() / 2 - 75 && mx > getWidth() / 2 - 45 && my < getHeight() / 2 - 50 && my > getHeight() / 2 - 20){
System.out.println("saved1 = true");
}
}
public void mouseReleased(MouseEvent e) {
}
}
}
I know that I've got some cleaning up to do
public abstract class GUI is your problem. You can't instantiate abstract classes.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can create a subclass and instantiate that though.
Below I included two of the classes in my Java program (Launcher and Controls). In the both classes, they create a JFrame, draw a background image, and add lines of text. I have looked at the code over and over, but for some reason the background image and the line of text are not appearing in the second class (Controls). Could anyone please explain to me why this is happening?
Launcher Class:
import hungerGames.Display;
import hungerGames.RunGame;
import hungerGames.input.InputHandler;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Launcher extends JFrame implements Runnable {
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 800;
private int height = 450;
boolean running = false;
Thread thread;
public Launcher(int id) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
startMenu();
}
public void updateFrame() {
if (InputHandler.dragged) {
Point p = getLocation();
if (InputHandler.MouseDX != InputHandler.MousePX || InputHandler.MouseDX != InputHandler.MousePX) {
setLocation(p.x + InputHandler.MouseDX - InputHandler.MousePX, p.y + InputHandler.MouseDY - InputHandler.MousePY);
}
}
}
public void startMenu() {
running = true;
thread = new Thread(this, "menu");
thread.start();
}
public void stopMenu() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
try {
renderMenu();
} catch (IllegalStateException e) {
System.out.println("Handled");
}
updateFrame();
}
}
private void renderMenu() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/main_menu.jpg")), 0, 0, 800, 450, null);
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 100 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new RunGame();
}
}
if (InputHandler.mouseX >= 50 && InputHandler.mouseX <= 320 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 10, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Controls();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 490 && InputHandler.mouseY >= 290 && InputHandler.mouseY <= 325) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 295, 30, 33, null);
if (InputHandler.MouseButton == 1) {
dispose();
new Credits();
}
}
if (InputHandler.mouseX >= 400 && InputHandler.mouseX <= 440 && InputHandler.mouseY >= 390 && InputHandler.mouseY <= 425) {
g.drawImage(ImageIO.read(Launcher.class.getResource("/pin.png")), 360, 395, 30, 33, null);
if (InputHandler.MouseButton == 1) {
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 30));
g.drawString("By Lawrence Zhao", 210, 275);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Play", 50, 325);
g.drawString("Controls and Options", 50, 425);
g.drawString("Credits", 400, 325);
g.drawString("Exit", 400, 425);
g.dispose();
bs.show();
}
}
Controls Class:
import hungerGames.Display;
import hungerGames.input.InputHandler;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Controls extends JFrame{
public static final long serialVersionUID = 1L;
protected JPanel window = new JPanel();
private int width = 720;
private int height = 450;
private Rectangle rResolution;
private Choice resolution = new Choice();
public Controls() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
InputHandler input = new InputHandler();
addKeyListener(input);
addFocusListener(input);
addMouseListener(input);
addMouseMotionListener(input);
renderControls();
drawButtons();
stopMenuThread();
}
private void stopMenuThread() {
Display.getLauncherInstance().stopMenu();
}
private void drawButtons() {
rResolution = new Rectangle(50,100, 100, 25);
resolution.setBounds(rResolution);
resolution.add("640, 400");
resolution.add("800, 600");
resolution.add("1024, 768");
resolution.select(1);
add(resolution);
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
try {
g.drawImage(ImageIO.read(Display.class.getResource("/controls.jpg")),0, 0, 720, 450, null);
if (InputHandler.mouseX >= 360 && InputHandler.mouseX <= 400 && InputHandler.mouseY >=270 && InputHandler.mouseY <=305) {
g.drawImage(ImageIO.read(Controls.class.getResource("/pin.png")),360,270, 30, 33, null);
if (InputHandler.MouseButton == 1) {
Display.selection = resolution.getSelectedIndex();
dispose();
new Launcher(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
It's clear that you don't understand how the buffering strategy is suppose to work.
I'd suggest you have a read through Double Buffering for some clues.
(ps, I don't have much experience with this side of the API either, but I got your code to work by simply reading through the above linked tut)
Update
Seems to work just fine for me...
Some notes.
Pre-load your images, otherwise you're wasting your time double buffering as the IO is going to slow you down.
Make sure your images exist and are begin loaded properly
.
public class BadPaint03 {
public static void main(String[] args) {
new BadPaint03();
}
public BadPaint03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Controls frame = new Controls();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public class Controls extends JFrame {
private int width = 720;
private int height = 450;
private Rectangle rResolution;
protected JPanel window = new JPanel();
private BufferedImage background;
public Controls() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (Exception e) {
e.printStackTrace();
}
setUndecorated(true);
setSize(new Dimension(width, height));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
renderControls();
try {
Thread.sleep(1000 / 24);
} catch (InterruptedException ex) {
Logger.getLogger(BadPaint03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}
private void renderControls() throws IllegalStateException {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 720, 450);
if (background != null) {
int x = (720 - background.getWidth()) / 2;
int y = (450 - background.getHeight()) / 2;
g.drawImage(background, x, y, null);
}
g.setColor(Color.WHITE);
g.setFont(new Font("Agency FB", 0, 40));
g.drawString("Exit", 400, 300);
g.dispose();
bs.show();
}
}
}