Related
This my code for the simple maze game. Its being compiled and class file of MazeGame.java and Board.java are being created but not of Player.java and Map.java. The code is being compiled error free but its not running. Please help me out.
//MazeGame.java
package mygame;
import javax.swing.*;
public class MazeGame {
public static void main(String[] args) {
new MazeGame();
}
public MazeGame() {
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.setSize(450,450);
f.setLocationRelativeTo(null);
f.add(new Board());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Board.java
package mygame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
private String Message="";
private Font font = new Font("Comic Sans",Font.BOLD,50);
public Board() {
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0; y<14; y++) {
for(int x=0; x<14; x++) {
if(m.getMap(x,y).equals("f")) {
g.drawImage(m.getFinish(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("g")) {
g.drawImage(m.getGrass(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("w")) {
g.drawImage(m.getWall(),x*32,y*32,null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()*32,p.getTileY()*32,null);
}
if(win)
{
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(Message,100,300);
}
}
public class Al extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode==KeyEvent.VK_W) || (keyCode==KeyEvent.VK_UP)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(0,-1);
}
}
if((keyCode==KeyEvent.VK_S) || (keyCode==KeyEvent.VK_DOWN)) {
if(!(m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))) {
p.move(0,1);
}
}
if((keyCode==KeyEvent.VK_A) || (keyCode==KeyEvent.VK_LEFT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(-1,0);
}
}
if((keyCode==KeyEvent.VK_D) || (keyCode==KeyEvent.VK_RIGHT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(1,0);
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")) {
Message = "WINNER!!!";
win = true;
}
repaint();
}
}
//Map.java
package mygame;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.*;
public class Map {
private Scanner s;
private String Map[] = new String[14];
private Image grass,wall,finish;
public Map() {
ImageIcon img = new ImageIcon("G://sonali_java//mygame//grass.png");
grass = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//wall.png");
wall = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public String getMap(int x,int y) {
String index = Map[y].substring(x,x+1);
return index;
}
public Image getGrass() {
return grass;
}
public Image getWall() {
return wall;
}
public Image getFinish() {
return finish;
}
public void openFile() {
try {
s= new Scanner(new File("G://sonali_java//mygame//Map.txt"));
}
catch(Exception e) {
System.out.println("Error Loading File!!!!");
}
}
public void readFile() {
while(s.hasNext()) {
for(int i=0; i<14; i++) {
Map[i] = s.next();
}
}
}
public void closeFile() {
s.close();
}
}
//Player.java
package mygame;
import java.awt.*;
public class Player {
private int tileX,tileY;
private Image player;
public Player() {
tileX=1;
tileY=1;
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
player = img.getImage();
}
public Image getPlayer() {
return player;
}
public int getTileX() {
return tileX;
}
public int getTileY() {
return tileY;
}
public void move(int dx, int dy) {
tileX += dx;
tileY += dy;
}
}
I dont want to be mad but you are defining different folder locations
in some places "G://sonali_java//mygane//object.png", check "mygaNe"
in some places "G://sonali_java//mygame//Map.txt", check "mygaMe"
Are you sure while loading it does not throw a NullPointerException ?
Are you aware that you can, place code like
public void draw(Graphics g){
g.drawImage(playerImg, getX(), getY(), null);
}
in your player class, thus leaving the player class with drawing the player and simply calling the players draw method inside your Board paint method? This can also be done for drawing the map. Remember to call the draw methods in the paint method.
ALSO, THIS
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
check your directory location
I am making a maze game in Java. I have made a maze board, A start point and a end point. When I reach the end point then it exit and show a winning message. But I can not add a time limitation. Suppose player have to reach the end point with 30 seconds otherwise he lose the game. Please help me.
Here is my code i have done so far.......
Maze.java
package Maze;
import javax.swing.JFrame;
public class Maze {
public static void main(String args[])
{
new Maze();
}
public Maze()
{
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.add(new Board());
f.setSize(460,480);
f.setLocationRelativeTo(f);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Board.java
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// #SuppressWarnings("serial")
#SuppressWarnings("serial")
public class Board extends JPanel implements ActionListener
{
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
long startTime = System.currentTimeMillis();
long elapsedTime;
//private String Message="";
//private Font font=new Font("Serif",Font.BOLD,50);
public Board()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime=elapsedTime/1000;
m= new Map();
p= new Player();
addKeyListener(new Al());
setFocusable(true);
timer=new Timer(25, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
if(m.getMap(p.getTileX(), p.getTileY()).equals("f"))
{
//Message="WINNER";
win=true;
}
if(elapsedTime>=5)
win=true;
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0;y<14;y++)
{
for(int x=0;x<14;x++)
{
if(m.getMap(x,y).equals("f"))
g.drawImage(m.getFinish(), x*32, y*32, null);
if(m.getMap(x, y).equals("w"))
g.drawImage(m.getWall(), x*32, y*32, null);
if(m.getMap(x, y).equals("g"))
g.drawImage(m.getGrass(), x*32, y*32, null);
}
}
g.drawImage(p.getPlayer(), p.getTileX()*32, p.getTileY()*32,null);
}
if(win)
{
g.drawImage(m.getWinn(), 32, 32, null);
// g.setColor(Color.ORANGE);
//g.setFont(font);
//g.drawString(Message, 150, 200);
}
}
public class Al extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keycode= e.getKeyCode();
if(keycode==KeyEvent.VK_UP ){
if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w")){
p.move( 0, -1);
}
}
if(keycode==KeyEvent.VK_DOWN ){
if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w")){
p.move( 0, 1);
}
}
if(keycode==KeyEvent.VK_LEFT ){
if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w")){
p.move( -1, 0);
}
}
if(keycode==KeyEvent.VK_RIGHT ){
if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w")){
p.move( 1, 0 );
}
}
}
/* public void keyRealeased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}*/
}
}
Map.java
package Maze;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.ImageIcon;
public class Map {
private Scanner m;
private String Map[]=new String[14];
private Image grass,wall,finish,winn;
public Map(){
ImageIcon img = new ImageIcon("C://project//7.jpg");
grass = img.getImage();
img = new ImageIcon("C://project//2.jpg");
wall = img.getImage();
img=new ImageIcon("C://project//hell.gif");
finish=img.getImage();
img=new ImageIcon("C://project//12.jpg");
winn=img.getImage();
openfile();
readfile();
closefile();
}
public Image getGrass()
{
return grass;
}
public Image getWall()
{
return wall;
}
public Image getFinish()
{
return finish;
}
public Image getWinn()
{
return winn;
}
public String getMap(int x, int y){
String index=Map[y].substring(x, x+1);
return index;
}
public void openfile(){
try {
m = new Scanner(new File("C://project//Map.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Error loading file.");
}
}
public void readfile(){
while(m.hasNext()){
for(int i=0;i<14;i++){
Map[i]=m.next();
}
}
}
public void closefile(){
m.close();
}
}
Player.java
package Maze;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player {
private int tilex,tiley;
private Image player;
public Player(){
ImageIcon img=new ImageIcon("C://project//5990.gif");
player=img.getImage();
tilex=1;
tiley=1;
}
public Image getPlayer(){
return player;
}
public int getTileX(){
return tilex;
}
public int getTileY(){
return tiley;
}
public void move(int dx, int dy ){
tilex += dx;
tiley += dy;
}
}
and here is the .txt file
Map.txt
wwwwwwwwwwwwww
wggggggwgggggw
wggwwggwgwwggw
wwgggwwwggwggw
wgwgggggggwwgw
wgggwggwwwgggw
wgggwgggwggwww
wggwggwwwggggw
wgwwgggggwwggw
wgggggwwwgwggw
wggwggggwgwwgw
wwwwgwwwwggwgw
wggggwgfgggggw
wwwwwwwwwwwwww
You can do a work around ,Add a timer class which will execute at x seconds and keep on calculating the total seconds in a variable and when the limit is crossed you can stop your program.
Im trying to create and RPG game based on the youtube series from TheBennyBox, and so far I have 8 classes, which are supposed to display a square with openGL and able to move the square around, although my square is not shwoing up on the screen. Here's my code for the important classes:
Main:
package com.base.engine;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import com.base.game.Game;
import static org.lwjgl.opengl.GL11.*;
public class Main {
private static Game game;
public static void main(String[] args){
initDisplay();
initGL();
initGame();
gameLoop();
}
private static void gameLoop(){
while(!Display.isCloseRequested()){
getInput();
update();
render();
}
}
private static void initGame(){
game = new Game();
}
private static void render() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
Display.update();
Display.sync(60);
game.render();
}
private static void update() {
game.update();
}
private static void getInput() {
game.getInput();
}
private static void initGL(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_DEPTH_TEST);
glClearColor(0,0,0,0);
}
private static void cleanUp(){
Display.destroy();
Keyboard.destroy();
}
private static void initDisplay(){
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
Keyboard.create();
Display.setVSyncEnabled(true);
} catch (LWJGLException ex) {
// TODO Auto-generated catch block
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null,ex);
}
}
}
Game:
package com.base.game;
import java.util.ArrayList;
import org.lwjgl.opengl.Display;
import com.base.engine.GameObject;
import com.base.game.gameobject.Player;
public class Game {
private ArrayList<GameObject> objects;
private Player player;
public Game(){
objects = new ArrayList<GameObject>();
player = new Player(Display.getWidth()/2-Player.SIZE/2,Display.getHeight()/2-Player.SIZE/2);
objects.add(player);
}
public void getInput(){
player.getInput();
}
public void update(){
for(GameObject go : objects){
go.update();
}
}
public void render(){
for(GameObject go : objects){
go.render();
}
}
}
GameObject:
package com.base.engine;
import static org.lwjgl.opengl.GL11.*;
public abstract class GameObject {
protected float x;
protected float y;
protected float sx;
protected float sy;
protected Sprite spr;
public void update(){
}
public void render(){
glPushMatrix();
{
glTranslatef(x,y,0);
spr.render();
}
glPopMatrix();
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getSx(){
return spr.getSx();
}
public float getSy(){
return spr.getSy();
}
protected void init(float x,float y,float r, float g, float b, float sx, float sy){
this.x=x;
this.y=y;
this.spr = new Sprite(r,g,b,sx,sy);
}
}
Sprite:
package com.base.engine;
import static org.lwjgl.opengl.GL11.*;
public class Sprite {
private float r;
private float g;
private float b;
private float sx;
private float sy;
public Sprite(float r,float g,float b,float sx,float sy){
this.g=g;
this.r=r;
this.b=b;
this.sx=sx;
this.sy=sy;
}
public void render() {
glColor3f(r,g,b);
glBegin(GL_QUADS);
{
glVertex2f(0,0);
glVertex2f(0,sy);
glVertex2f(sx,sy);
glVertex2f(sx,0);
}
glEnd();
}
public float getSx(){
return sx;
}
public float getSy(){
return sy;
}
public void setSx(float sx){
this.sx = sx;
}
public void setSy(float sy){
this.sy=sy;
}
}
Player:
package com.base.game.gameobject;
import org.lwjgl.input.Keyboard;
import com.base.engine.GameObject;
import com.base.engine.Sprite;
public class Player extends GameObject{
public static final float SIZE = 32;
public Player(float x, float y){
init(x,y,0.1f,1f,0.25f,SIZE,SIZE);
}
public void getInput(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
move(0,1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)){
move(0,-1);
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)){
move(-1,0);
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
move(0,1);
}
}
private void move(float magX,float magY){
x += getSpeed()-magX;
y += getSpeed()-magY;
}
public float getSpeed(){
return 4f;
}
}
And there are others but these are the most important. Sorry for so much code..i just don't know whats going wrong.
I'm not an expert on LWJGL, bit normally you call the sync functions after you rendered. The way it's currently written I presume that you draw the picture after buffer swap (i.e. after contents of the framebuffer were sent to the screen) but the next render iteration will clear it. Try reordering a few things:
private static void render() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
game.render();
Display.update();
Display.sync(60);
}
Note that a lot of other things skewed as well. The standard preamble of a frame render iteration is setting up the viewport and the projection. I.e. the whole code in your initGL belongs at the begin of render.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
trying to get more fps from this jogl program. theoretical fps is very high, but actual fps is low. jvisualvm says that most (over 90%) of the time is spent in AWTAnimatorImpl.display() & GLDrawableHelper.displayImpl().
package stanalone;
import static java.awt.Color.cyan;
import static java.awt.Color.magenta;
import static java.awt.Color.white;
import static java.awt.Color.yellow;
import static java.awt.Color.red;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
import static java.lang.Math.min;
import static java.lang.Math.signum;
import static java.lang.Math.sin;
import static javax.media.opengl.GL.GL_ARRAY_BUFFER;
import static javax.media.opengl.GL.GL_COLOR_BUFFER_BIT;
import static javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT;
import static javax.media.opengl.GL.GL_DEPTH_TEST;
import static javax.media.opengl.GL.GL_FLOAT;
import static javax.media.opengl.GL.GL_FRONT;
import static javax.media.opengl.GL.GL_FRONT_AND_BACK;
import static javax.media.opengl.GL.GL_LEQUAL;
import static javax.media.opengl.GL.GL_MAX_TEXTURE_SIZE;
import static javax.media.opengl.GL.GL_NICEST;
import static javax.media.opengl.GL.GL_POINTS;
import static javax.media.opengl.GL.GL_WRITE_ONLY;
import static javax.media.opengl.GL2ES1.GL_PERSPECTIVE_CORRECTION_HINT;
import static javax.media.opengl.GL2GL3.GL_FILL;
import static javax.media.opengl.fixedfunc.GLLightingFunc.GL_SMOOTH;
import static javax.media.opengl.fixedfunc.GLMatrixFunc.GL_MODELVIEW;
import static javax.media.opengl.fixedfunc.GLMatrixFunc.GL_PROJECTION;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLJPanel;
import javax.media.opengl.fixedfunc.GLLightingFunc;
import javax.media.opengl.fixedfunc.GLPointerFunc;
import javax.media.opengl.glu.GLU;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.util.FPSAnimator;
import com.jogamp.opengl.util.gl2.GLUT;
class Histogram {
public Histogram() {
this(10,0,1);
}
public Histogram(int bins,double low,double high) {
this.bins=bins;
bin=new int[bins];
this.low=low;
this.high=high;
range=high-low;
}
public void add(double[] x) {
for(int i=0;i<x.length;i++)
add(x[i]);
}
public void add(double x) {
n++;
sum+=x;
final double x2=x*x;
sum2+=x2;
min=Math.min(min,x);
max=Math.max(max,x);
if(x>=high)
overflows++;
else if(x<low)
underflows++;
else {
double val=x-low;
int index=(int)(bins*(val/range));
bin[index]++;
}
}
public void clear() {
for(int i=0;i<bins;i++)
bin[i]=0;
overflows=0;
underflows=0;
min=Double.MAX_VALUE;
max=Double.MIN_VALUE;
}
public int n() {
return n;
}
public double low() {
return low;
}
public double high() {
return high;
}
public double range() {
return high()-low();
}
public int bins() {
return bins;
}
public double min() {
return n==0?Double.NaN:min;
}
public double max() {
return n==0?Double.NaN:max;
}
public double sum() {
return n==0?Double.NaN:sum;
}
public double mean() {
return n==0?Double.NaN:sum/n;
}
public double variance() {
return n==0?Double.NaN:sum2/n-mean()*mean();
}
public int bin(int index) {
if(index<0)
return underflows;
else if(index>=bins)
return overflows;
else return bin[index];
}
public double maxDifference() {
double max=0;
for(int i=0;i<bins();i++)
max=Math.max(max,Math.abs(bin(i)-n()/(double)bins())/(n()/(double)bins()));
return max;
}
public String toString() {
final StringBuffer sb=new StringBuffer();
sb.append((float)min()).append("<=").append((float)mean()).append("<=").append((float)max()).append(" ");
sb.append(bin(-1)).append(",[");
for(int i=0;i<bins;i++)
sb.append(i>0?",":"").append(bin(i));
sb.append("],").append(bin(bins));
return sb.toString();
}
private int[] bin;
private int n,bins,underflows,overflows;
private final double low,high,range;
private double min=Double.MAX_VALUE,max=Double.MIN_VALUE,sum,sum2;
}
class MyDataObject {
MyDataObject(Point2D[] points) {
this(points,white);
}
MyDataObject(Point2D[] points,Color color) {
this.points=points;
this.color=color;
}
Point2D[] points;
Color color;
static Point2D[] randomPoints(Random random,Point2D offset) {
List<Point2D> l=new LinkedList<Point2D>();
int n=nPoints/pieces.length;
for(int j=0;j<n;j++)
l.add(new Point2D.Double(offset.getX()+random.nextFloat(),offset.getY()+random.nextFloat()));
return l.toArray(new Point2D[0]);
}
static MyDataObject[] pieces;
static Color[] colors=new Color[]{cyan,magenta,yellow,white};
static int nPoints=1000000;
}
class StandAlone implements GLEventListener {
StandAlone(GLAutoDrawable drawable) {
this.drawable=drawable;
drawable.addGLEventListener(this);
init();
}
void init() {
nVbos=4;
vertexBufferIndices=new int[nVbos];
for(int i=0;i<vertexBufferIndices.length;i++)
vertexBufferIndices[i]=-1;
numberOFVertices=new int[nVbos];
// drawAxes=true;
MyDataObject.pieces=new MyDataObject[nVbos];
for(int i=0;i<nVbos;i++) {
Point2D offset=new Point.Double(min(0,signum(cos(PI/4+i*PI/2))),min(0,signum(sin(PI/4+i*PI/2))));
MyDataObject.pieces[i]=new MyDataObject(MyDataObject.randomPoints(random,offset),MyDataObject.colors[i%MyDataObject.colors.length]);
}
}
static void setupFrame(Component component) {
setupFrame(component,defaultFps);
}
static void setupFrame(Component component,int fps) {
component.setPreferredSize(new Dimension(displayWidth,displayHeight));
final FPSAnimator animator=new FPSAnimator((GLAutoDrawable)component,fps,true);
final JFrame frame=new JFrame();
frame.getContentPane().add(component);
frame.addWindowListener(new WindowAdapter() {
#Override public void windowClosing(WindowEvent e) {
new Thread() {
#Override public void run() {
if(animator.isStarted())
animator.stop();
System.exit(0);
}
}.start();
}
});
frame.setTitle(TITLE);
frame.pack();
frame.setVisible(true);
animator.start();
}
static void setup() {
GLProfile glprofile=GLProfile.getDefault();
GLCapabilities glcapabilities=new GLCapabilities(glprofile);
GLJPanel panel=new GLJPanel(glcapabilities);
new StandAlone(panel);
setupFrame(panel,200);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
setup();
}
});
}
private void createVbo(GL2 gl2,int[] n,int index) {
if(!gl2.isFunctionAvailable("glGenBuffers")||!gl2.isFunctionAvailable("glBindBuffer")||!gl2.isFunctionAvailable("glBufferData")||!gl2.isFunctionAvailable("glDeleteBuffers")) { throw new RuntimeException("Vertex buffer objects not supported."); }
gl2.glGenBuffers(1,vertexBufferIndices,index);
// create vertex buffer data store without initial copy
gl2.glBindBuffer(GL_ARRAY_BUFFER,vertexBufferIndices[index]);
gl2.glBufferData(GL_ARRAY_BUFFER,n[0]*3*Buffers.SIZEOF_FLOAT*2,null,GL.GL_DYNAMIC_DRAW);
}
private static void storeVerticesAndColors(FloatBuffer floatbuffer,MyDataObject w) {
for(Point2D p:w.points) {
floatbuffer.put((float)p.getX()).put((float)p.getY()).put(0);
floatbuffer.put((float)(w.color.getRed()/255.));
floatbuffer.put((float)(w.color.getGreen()/255.));
floatbuffer.put((float)(w.color.getBlue()/255.));
}
floatbuffer.rewind();
}
private void fillVertexBuffer(GL2 gl2,MyDataObject piece,int index) {
// map the buffer and write vertex and color data directly into it
gl2.glBindBuffer(GL_ARRAY_BUFFER,vertexBufferIndices[index]);
ByteBuffer bytebuffer=gl2.glMapBuffer(GL_ARRAY_BUFFER,GL_WRITE_ONLY);
FloatBuffer floatbuffer=bytebuffer.order(ByteOrder.nativeOrder()).asFloatBuffer();
storeVerticesAndColors(floatbuffer,piece);
gl2.glUnmapBuffer(GL_ARRAY_BUFFER);
}
protected int createAndFillVertexBuffer(GL2 gl2,MyDataObject piece,int index) {
int[] n=new int[]{piece.points.length};
if(vertexBufferIndices[index]==-1)
createVbo(gl2,n,index);
fillVertexBuffer(gl2,piece,index);
return n[0];
}
private void renderPiece(GLAutoDrawable drawable,int index) {
final GL2 gl2=drawable.getGL().getGL2();
gl2.glColorMaterial(GL_FRONT_AND_BACK,GLLightingFunc.GL_AMBIENT_AND_DIFFUSE);
gl2.glEnable(GLLightingFunc.GL_COLOR_MATERIAL);
// draw all objects in vertex buffer
gl2.glBindBuffer(GL_ARRAY_BUFFER,vertexBufferIndices[index]);
gl2.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
gl2.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl2.glVertexPointer(3,GL_FLOAT,6*Buffers.SIZEOF_FLOAT,0);
gl2.glColorPointer(3,GL_FLOAT,6*Buffers.SIZEOF_FLOAT,3*Buffers.SIZEOF_FLOAT);
gl2.glPolygonMode(GL_FRONT,GL_FILL);
gl2.glDrawArrays(GL_POINTS,0,1*numberOFVertices[index]);
// disable arrays once we're done
gl2.glBindBuffer(GL_ARRAY_BUFFER,0);
gl2.glDisableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
gl2.glDisableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl2.glDisable(GLLightingFunc.GL_COLOR_MATERIAL);
}
private void startTimeReporting() {
t0=System.nanoTime();
if(frame%reportPeriod==0)
t0Frame=t0;
if(frame>1) {
double dt=(System.nanoTime()-t0Display);
double millis=dt/1000000.;
hDisplay.add(millis);
}
}
void endTimeReporting() {
double dt=(System.nanoTime()-t0);
double millis=dt/1000000.;
hRender.add(millis);
if(++frame%reportPeriod==0) {
System.out.println("average render time: "+hRender.mean()+" ms., max fps="+1000./hRender.mean());
double dtFrames=System.nanoTime()-t0Frame;
System.out.println("average time between calls to display: "+hDisplay.mean()+" ms., actual fps="+reportPeriod/(dtFrames/1000000.)*1000.);
hRender.clear();
}
t0Display=System.nanoTime();
}
void update() {
angle+=1;
}
#Override public void reshape(GLAutoDrawable drawable,int x,int y,int width,int height) {
System.out.println("super.reshape "+drawable);
GL2 gl=drawable.getGL().getGL2();
if(height==0)
height=1;
float aspect=(float)width/height;
gl.glViewport(0,0,width,height);
gl.glMatrixMode(GL_PROJECTION);
gl.glLoadIdentity();
// glu.gluPerspective(45.0,aspect,0.1,100.0);
gl.glMatrixMode(GL_MODELVIEW);
gl.glLoadIdentity();
}
#Override public void init(final GLAutoDrawable drawable) {
GL2 gl=drawable.getGL().getGL2();
glu=new GLU();
glut=new GLUT();
gl.glClearColor(0.0f,0.0f,0.0f,0.0f);
gl.glClearDepth(1.0f);
gl.glEnable(GL_DEPTH_TEST);
gl.glDepthFunc(GL_LEQUAL);
gl.glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
gl.glShadeModel(GL_SMOOTH);
for(int i=0;i<nVbos;i++)
numberOFVertices[i]=createAndFillVertexBuffer(drawable.getGL().getGL2(),MyDataObject.pieces[i],i);
}
#Override public void display(GLAutoDrawable drawable) {
update();
if(doTimeReporting)
startTimeReporting();
GL2 gl=drawable.getGL().getGL2();
gl.glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glRotated(angle,0,1,0);
gl.glColor3d(1,1,1);
for(int i=0;i<nVbos;i++)
renderPiece(drawable,i);
if(doTimeReporting)
endTimeReporting();
}
#Override public void dispose(GLAutoDrawable drawable) {}
final GLAutoDrawable drawable;
double angle;
int nVbos;
int[] vertexBufferIndices;
int[] numberOFVertices;
Random random=new Random();
final int reportPeriod=100;
boolean doTimeReporting=true;
long t0,t0Frame,t0Display;
int frame;
Histogram hRender=new Histogram(10,0,10),hDisplay=new Histogram(10,0,100);
int fps=defaultFps;
protected GLU glu;
protected GLUT glut;
protected static String TITLE="JOGL 2.0 Setup (GLJPanel)";
protected static final int displayWidth=1024;
protected static final int displayHeight=1024;
protected static final int defaultFps=60;
}
If most of the processing power is being put to use in the display code, chances are you're using too many vertices or complex texture calculations. Texture-wise, it is better to set the textures to objects on initialization where possible, so that you're program only has to load them once and it's done. For the vertices, be sure you aren't accidentally duplicating anything, and try to limit particle effects, because that can be very expensive with processing.
You seem to misunderstand how OpenGL works. It's mostly useless to measure the time taken to wrap your OpenGL calls, as you are currently doing.
When you call an opengl command, it just puts the command into a processing queue and returns. The actual time it takes to draw the object is not the amount of time it takes you to issue all the draw calls.
If the time between calls to display is 37ms, than that's how long it takes the GPU to process all of the commands that you've queued to it.
I am making a game (see my previous threads) and have encountered a lot of problems on the way. All I know is that he code compiles, runs, but nothing appears in the window, it's just grey. At Andrew Thompson's suggestion, I am posting the entire compilable version here. Sorry for the length but it is ALL the code in the program. And a lot of things will probably not make sense (unused ActionPerformed to name one), partially because I implemented code in the event that I would need it but mostly because I have never done this before.
Also, so far I have no multithreading, because once again, I am new to this, so ideally I would like to keep it that way, if only for the sake of my sanity.
EDIT: Forgot to mention I have 4 PNGs in there representing the 4 different objects that appear. My code is flexible enough for you to supply your own. Here is the image I am using for ships and here is the one for bullets just make copies, put them the source file and name them "Enemy-ship" "ship2" "Ebullet" and "PBullet"
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JFrame;
public class GameController extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -3599196025204169130L;
private static GameView window;
private static Timer time;
public GameController()
{
setTitle("Space Shooter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
//window = new GameView(800,600);
//window.setVisible(true);
//
}
//TODO spawn
/*public static void main(String args[])
{
//GameController c = new GameController();
window = new GameView(800,600);
window.setVisible(true);
time = new Timer(40, this);
time.schedule( new TimerTask(){
public void run(){GameState.update();
window.paintComponents(null);}
},0, 40);
}*/
public void display() {
add(new GameView(800,600));
pack();
setMinimumSize(getSize());// enforces the minimum size of both frame and component
setVisible(true);
}
public static void main(String[] args) {
GameController main = new GameController();
main.display();
time = new Timer(40, main);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e instanceof EndEvent)//TODO fix this
{
}
else
{
repaint();
}
}
}
package Game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameView extends JComponent implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -2869672245901003704L;
private static final Graphics Graphics = null;
private boolean liveGame;//used so that buttons cannot be clicked after game is complete
private GameState gs;
private Player p;
private int w, h;
public GameView(int width, int height)
{
liveGame = true;
gs = new GameState();
GameState.init(width, height);
p = new Player(width/2,(height*7)/8);
this.setBackground(Color.BLACK);
paintComponents(Graphics);
w = width;
h = height;
}
#Override
public Dimension getMinimumSize() {
return new Dimension(w, h);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.black);
GameState.update();
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
public void paintComponents (Graphics g)
{
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
this.paint(g);
}
public void refreshImage()
{
this.removeAll();
paintComponents(Graphics);
}
public void actionPerformed(ActionEvent e) {
}
}
package Game;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
public class GameState {
private static ArrayList<Bullet> playBullets;
public static ArrayList<Bullet> getPlayBullets() {
return playBullets;
}
public static ArrayList<Bullet> getEnBullets() {
return enBullets;
}
public static ArrayList<Enemy> getEnemies() {
return enemies;
}
public static Player getP() {
return p;
}
private static ArrayList<Bullet> enBullets;
private static ArrayList<Enemy> enemies;
private static int X, Y;//for limit of screen so nothing can go outside of screen
private static Player p;
private static int score;
public GameState(){
}
public static void init(int x, int y)
{
playBullets = new ArrayList<Bullet>();
enBullets = new ArrayList<Bullet>();
enemies = new ArrayList<Enemy>();
X=x;
Y=y;
p = null;
score =0;
}
public static int xLimit(){return X;}
public static int yLimit(){return Y;}
public static int getScore(){return score;}
public static void add (Location e)
{
if(e instanceof Bullet)
{
if(((Bullet) e).getOwner() instanceof Enemy){
enBullets.add((Bullet) e);
}
else
playBullets.add((Bullet) e);
}
else if(e instanceof Enemy){enemies.add((Enemy)e);}
else
p=(Player)e;
}
public static void spawn()
{
Enemy e = new Enemy(((int)(Math.random()*(X-56))+28), 0, 1);
}
public static void playerCD()//detects if player has collided with anything, removes whatever collided with it, and causes the player to take damage
{
if(enemies.size()>0){
for(int i =0; i < enemies.size(); i++)
{
if (p.getLocation().intersects(enemies.get(i).getLocation()))
{
p.takeDamage(enemies.get(i).getDamage());
enemies.get(i).takeDamage(p.getDamage());
}
}
if(enBullets.size()>0)
for(int i =0; i < enBullets.size(); i++)
{
if (p.getLocation().intersects(enBullets.get(i).getLocation()))
{
p.takeDamage(enBullets.get(i).getDamage());
enBullets.remove(i);
i--;
}
}
}
}
public static void enemyCD()
{
for(int i =0; i < enemies.size(); i++)
{
for(int n =0; n < playBullets.size(); n++)
{
if (playBullets.get(n).getLocation().intersects(enemies.get(i).getLocation()))
{
enemies.get(i).takeDamage(playBullets.get(i).getDamage());
playBullets.remove(n);
n--;
score+=50;
}
}
}
}
public static void checkForDead()//clears away dead and things gone offscreen
{
for(int i =0; i < enemies.size(); i++)
{
if(enemies.get(i).getY()>Y)
{
enemies.remove(i);
i--;
}
}
for(int i =0; i < enBullets.size(); i++)
{
if(enBullets.get(i).getY()>Y)
{
enBullets.remove(i);
i--;
}
}
for(int i =0; i < enemies.size(); i++)
{
if(enemies.get(i).getHealth()>0)
{
enemies.remove(i);
i--;
score+=200;
}
}
if(p.getHealth()<=0)
{
ActionEvent e = new EndEvent(null, 0, "end");
}
}
public static void update()
{
move();
playerCD();
enemyCD();
checkForDead();
}
public static void move()
{
p.move();
for(int i =0; i < enemies.size(); i++){enemies.get(i).move();}
for(int i =0; i < enBullets.size(); i++){enBullets.get(i).move();}
for(int i =0; i < playBullets.size(); i++){playBullets.get(i).move();}
}
}
package Game;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
public abstract class Fights extends Location implements ActionListener {
public Fights(Rectangle location) {
super(location);
// TODO Auto-generated constructor stub
}
public Fights(){}
protected int health;
protected int maxHealth;//in the event that I want to have healing items
protected int shotCooldown;//in milliseconds
protected int shotDmg;
protected long currentCool; //cooldown tracker, represents time that shot will be cooled down by (System time # last shot + shotCooldown
protected int xVel, yVel;
public abstract boolean shoot();
public abstract int takeDamage(int damage);//returns remaining health
protected boolean shoots;//determines whether thing can shoot. possible implementation in some enemy class
public boolean move;
public int getHealth(){return health;}
public abstract boolean move();
public int getDamage(){return shotDmg;}
public boolean isDead()
{
return health<=0;
}
}
package Game;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
public class Location {
protected Rectangle loc;
protected Image image;
public Location(){};
public Location (Rectangle location)
{
loc = location;
}
public Rectangle getLocation()
{
return loc;
}
public void setLocation(Rectangle l)
{
loc = l;
}
public void updateLocation(int x, int y)
{
loc.setLocation(x, y);
}
public Image getImage()
{
return image;
}
public int getX()
{
return (int)loc.getX();
}
public int getY()
{
return (int)loc.getY();
}
}
package Game;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player extends Fights implements KeyListener{
int speed = 4;
public Player(Rectangle location) {
super(location);
GameState.add(this);
image = null;
try{
image = ImageIO.read(new File("ship2.png"));
}catch(IOException e){}
}
public Player(int x, int y) {
maxHealth = 1;
health = maxHealth;
image = null;
try{
image = ImageIO.read(new File("ship2.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(x, y, image.getWidth(null), image.getHeight(null)));
GameState.add(this);
}
public void resetVelocity()
{
xVel = 0;
yVel = 0;
}
#Override
public boolean shoot() {
if(currentCool - System.currentTimeMillis() >0){return false;}
else
{
new Bullet(this);
currentCool = System.currentTimeMillis() + shotCooldown;
}//spawns bullet in the center and slightly in front of player
return true;
}
#Override
public int takeDamage(int damage) {
return health-=damage;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean move() {//moves in a direction only if it won't exceed screen boundary, boolean just in case i need it later
int newX = this.getX(), newY=this.getY();
if((xVel+ this.getX()+this.getLocation().width)<GameState.xLimit()&& this.getX()+xVel>=0)
{
newX +=xVel;
}
if((yVel+ this.getY()+this.getLocation().height)<GameState.yLimit()&& this.getY()+yVel>=0)
{
newY +=yVel;
}
this.updateLocation(newX, newY);
this.resetVelocity();
return true;
}
#Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode()== KeyEvent.VK_LEFT)
{
xVel -= speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_RIGHT)
{
xVel += speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_UP)
{
yVel -= speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_DOWN)
{
yVel += speed;
}
if(arg0.getKeyCode()==KeyEvent.VK_SPACE)
{
this.shoot();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
package Game;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Enemy extends Fights {
public Enemy(Rectangle location) {
super(location);
GameState.add(this);
image = null;
try{
image = ImageIO.read(new File("Enemy-Ship.png"));
}catch(IOException e){}
}
public Enemy(int x, int y, int d) {
image = null;
try{
image = ImageIO.read(new File("Enemy-Ship.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(x, y, image.getWidth(null), image.getHeight(null)));
GameState.add(this);
shotCooldown =(int)(Math.random()*2000);
xVel = (int)((Math.pow(-1, (int)(Math.random())))*((int)(Math.random()*6))+2);
yVel = (int)(Math.random()*3+1);
shotDmg =d;
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean shoot() {
if(currentCool - System.currentTimeMillis() >0){return false;}
else
{
new Bullet(this);
currentCool = System.currentTimeMillis() + shotCooldown;
}//spawns bullet in the center and slightly in front of player
return true;
}
#Override
public int takeDamage(int damage)//returns remaining health
{
health = health-damage;
return health;
}
#Override
public boolean move() {
int newX = this.getX(), newY=this.getY();
if((xVel+ this.getX()+this.getLocation().width)<GameState.xLimit()&& this.getX()+xVel>=0)
{
xVel=-xVel;
newX +=xVel;
}
if(this.getY()+yVel>=0)
{
newY +=yVel;
}
this.updateLocation(newX, newY);
return true;
}
}
package Game;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Bullet extends Location{
private Fights bulletOwner;
private int damage;
private int velocity;
public Bullet(Fights owner)//eventually change to singleton pattern for efficiency
{
bulletOwner = owner;
damage = owner.getDamage();
image = null;
if(owner instanceof Enemy)
{
try{
image = ImageIO.read(new File("Ebullet.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(owner.getX(), owner.getY()+((int)(owner.getLocation().getHeight()/2)), image.getWidth(null), image.getHeight(null)));
velocity = 5;
}
else
{
try{
image = ImageIO.read(new File("Pbullet.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(owner.getX(), owner.getY()-((int)(owner.getLocation().getHeight()/2)), image.getWidth(null), image.getHeight(null)));
velocity = -15;
}
GameState.add(this);
}
public Fights getOwner(){return bulletOwner;}
public int getDamage(){return damage;}
public int getVelocity(){return velocity;}
public boolean move()
{
this.updateLocation(this.getX(), this.getY()+velocity);
return true;
}
}
I can't believe your write 700 lines of code without doing any testing along the way. Its time you go back to the beginning and start with something simple. That is the whole point of a SSCCE. Start with painting a couple of compononents. Once you get that working you add some movement. Once that is working you add collision logic.
The only thing I noticed with a quick broswe is that you override paintComponents(). There is no need to do that custom painting is done in the pantComponent() method.
If you can't produce a smaller sized SSCCE, then all I can do is wish you good luck.
Ok, so I think I have figured most of it out.
You have a couple problems.
First, you should only see a grey screen with a black rectangle in the middle since you have nothing in your Bullet and Enemy Arrays. This is what I got when I ran your code (after removing references to endEvent cuz it couldn't find it). So to fix this, just give it something to draw
The second problem is apparent once you give it something to draw. I manually put in a line of code to draw the Player, for which I used one of my own pngs. When you do this it will fail to compile with a null pointer exception. The reason is because in your GameView class, you have your Graphics object called "graphics" set to null, but then you proceed to call paintComponents(graphics). As mentioned before, this only compiled before because you never actually drew anything. To fix this, you can just remove
public void paintComponents (Graphics g)
{
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
this.paint(g);
}
and let the overridden paintComponent(Graphics g) method above it do all the work. Additionally, instead of the paintComponents(graphics) calls, use repaint(). Also you can get rid of the first call to paintComponents(graphics) in the constructor as it will paint the first time by default. If you really want to use your own method then you have to create a Graphics object and pass that in.
Lastly, in the overridden paintComponents(Graphics g) method, you have the last line being to draw the giant black box. This will then cover up anything you've drawn before. So you should have that as the first line and draw everything else in order such that the thing you want to be on top should be drawn last. I was able to get my test image to show up with the following code for that class. I don't think I changed anything else.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameView extends JComponent implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -2869672245901003704L;
private boolean liveGame;//used so that buttons cannot be clicked after game is complete
private GameState gs;
private Player p;
private int w, h;
public GameView(int width, int height)
{
liveGame = true;
gs = new GameState();
GameState.init(width, height);
p = new Player(width/2,(height*7)/8);
this.setBackground(Color.BLACK);
w = width;
h = height;
}
#Override
public Dimension getMinimumSize() {
return new Dimension(w, h);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.black);
GameState.update();
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
g.drawImage(p.getImage(),p.getX(),p.getY(),null);
}
public void refreshImage()
{
this.removeAll();
repaint();
}
public void actionPerformed(ActionEvent e) {
}
}
The other thing is in some of your other classes you have #Override over the actionPerformed method. My IDE doesn't like that, although it does compile. It says "#Override is not allowed when implementing interface methods."
Hopefully this works for you.
try adding repaint(); after you make a change to a content pane. I dont think concurrency is going to be a problem unless you clog up your EDT.