Hi,
I am currently working on curling game for my High School assignment and i have lots of files of code, so i doubt anyone will want to look through them.
Im having an issue in which, i have a JPanel and when i call the paintComponent (Graphics g) of that class, it actually goes inside the method (so the method is called), however it will not display the pictures that i have drawn onto the screen (using drawImage).
I havn't had this problem before, and the previous night it was working fine, but when i added more classes and modified some stuff its not working now.
I would be very appreciative if anyone could help me with is issue ASAP.
ill copy the main files that i havve:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import java.util.*;
/**
* RockMotion is the class that contains the "launching" effect of the Curling Rocks.
* The background playing field is displayed on a JPanel, and so is an image of the current Rock.
* When a keyboard input is detected, the rock launches using specific information, constructed in the contructer, such as velocity and momentum.
* @author Arash Khazaei
* @version 1.2
*/
public class RockMotionReal extends JPanel
{
private boolean powerSelected, directionSelected;
ArrayList <Rock> listOfRocks = new ArrayList <Rock> ();
/**
* A random textfield that is added, to fix the KeyListener.
*/
JTextField random;
/**
* A boolean to determine whether background has been drawn or not.
*/
boolean drawOnce;
/**
* A Final integer on the Number of Rocks.
*/
// public static final int MAX_PARTICLES = 1;
/**
* Height of the display Screen.
*/
public static final int WIDTH = 1280;
private double resizeRate;
/**
* Height of the display Screen.
*/
public static final int HEIGHT = 700;
private int updateXCoord;
private int updateYCoord;
private int updateWidth;
private int updateHeight;
private Player player1;
private Player player2;
boolean running = false;
long startTime = 0, lastTime;
long delay = 50, delta, advanceRate;
/**
* Array of Rocks.
*/
// Rock[] rocks = new Rock [MAX_PARTICLES];
/**
* The current Rock, that is being delt with.
*/
Rock currentRock;
/**
* The constant value for the friction of the ice, which will be subtracted from the momentum of the Rock.
*/
private final double FRICTION = 0.4;
/**
* The name of the background Image that needs to be used.
*/
private String view;
private boolean firstImage;
/**
* This method finds the distance of two objects.
*
* @param x1 The 1st x-coordinate.
* y1 The 1st y-coordinate.
* x2 The 2nd x-coordinate.
* y2 The 2nd y-coordinate.
* @return The distance between the two sets of coordinates.
*/
public double distance (double x1, double y1, double x2, double y2)
{
return Math.sqrt ((Math.pow ((x2 - x1), 2)) + (Math.pow ((y2 - y1), 2)));
}
/**
*Constructor that will create the JPanel and initiate .
* This will set a certain value to the velocity of the Rock, calculate the momentum, determine the type of Rock, and select the image of the background.
* A KeyListener will be added as well to detect the input of the user.
* This will also initiate the set of Curling Rocks.
*/
public RockMotionReal (ArrayList <Rock> firstToGo, ArrayList <Rock> secondToGo, Player player1, Player player2)
{
super ();
firstImage = true;
setDoubleBuffered (true);
drawOnce = false;
Dimension screenSize = Toolkit.getDefaultToolkit ().getScreenSize (); //gets the size of the monitor
setPreferredSize (new Dimension (WIDTH,HEIGHT)); //remove -30 to make it full screen
// for (int x = 0 ; x < MAX_PARTICLES ; x++)
// {
// rocks [x] = new Rock ((screenSize.width/2) - 15, 610, "Rock_Red", 50, 45, 0, 10);
// }
// rocks [0] = new Rock (410, 560, "Rock_Yell", 50, 45, 0, 10);
// rocks [0] = new Rock ((WIDTH/2) + 5,
// HEIGHT - 122, "Rock_Red", 55, 50, 0, 10);
view = "VIEW_UPDATE";
currentRock = firstToGo.get (0);
listOfRocks.addAll (firstToGo);
listOfRocks.addAll (secondToGo);
this.player1 = player1;
this.player2 = player2;
updateXCoord = 0;
updateYCoord = -4;
updateWidth = WIDTH;
updateHeight = HEIGHT;
setVisible (true);
}
// animation code
// This starts the threads.
public void startClock ()
{
lastTime = startTime = System.currentTimeMillis ();
//time = 0.;
running = true;
}
//
//
// public void stop ()
// {
// running = false;
// }
public double putDelay ()
{
delta = System.currentTimeMillis () - lastTime;
lastTime += delta;
startTime += delay;
try
{
Thread.sleep (Math.max (0, startTime - System.currentTimeMillis ()));
}
catch (InterruptedException e)
{
}
return (delta / 1000.);
}
// void advanced (double dt)
// {
// s.collision (m);
// m.advanced (dt);
// s.advanced (dt);
// running = m.check (s);
// if (level < 2)
// {
// gb.setColor (Color.red);
// gb.drawLine (xx = m.X () + size, yy = m.Y () + size, xx, yy);
// gb.setColor (Color.blue);
// gb.drawLine (xx = s.X () + size, yy = s.Y () + size, xx, yy);
// }
// repaint ();
// }
public Rock getRock ()
{
return currentRock;
}
//
// /**
// *Calls the launch method, when a key is pressed.
// *
// *@param e The KeyEvent that occurs.
// */
// public void keyPressed (KeyEvent e)
// {
// //System.out.println ("RAN KEY");
// if (!directionSelected)
// {
// directionSelected = true;
// }
// if (directionSelected && !powerSelected)
// {
// powerSelected = true;
// }
// if (powerSelected)
// actualRunning ();
// }
//
//
// /**
// * Empty methods for other Key Events.
// *
// * @param e The KeyEvent that occurs.
// */
// public void keyReleased (KeyEvent e)
// {
// }
//
//
// /**
// * Empty methods for other Key Events.
// *
// * @param e The KeyEvent that occurs.
// */
// public void keyTyped (KeyEvent e)
// {
// }
//
/**
* Paints the background.
* <p>
* Creates an image for the background and the Curling Rock, and draws it onto the JPanel, using drawImage.
* @param page allows access to graphics
*/
public void paintComponent (Graphics page)
{
super.paintComponent(page);
Image background = loadImage ("K:\\JAVA_FINAL_ISP\\Resources\\JAVA_ISP_ROCKS\\" + view + ".png");
Image rock;
page.drawImage (background, updateXCoord,updateYCoord, updateWidth, updateHeight, null);
page.fillOval (200,200,200,200);
for (Rock rocks: listOfRocks)
{
System.out.println (rocks.getPicName ());
rock = loadImage ("K:\\JAVA_FINAL_ISP\\Resources\\JAVA_ISP_ROCKS\\" + rocks.getPicName () + ".png");
page.drawImage (rock, (int) (rocks.getXPosition () - (rocks.getWidth ()/2)), (int) (rocks.getYPosition () - (rocks.getWidth ()/2)), (int) rocks.getWidth (), (int) rocks.getHeight (),this);
}
}
/**
*Returns the Image that is found at the given location of the picture.
*
*@param picLocation The location of the image that is required to be loaded.
*@return The Image at the specific location.
*/
public Image loadImage (String picLocation) //Loads the picture needed
{
Image pic = Toolkit.getDefaultToolkit ().getImage (picLocation);
MediaTracker tracker = new MediaTracker (new Frame ());
tracker.addImage (pic, 0);
try
{
tracker.waitForAll ();
}
catch (InterruptedException e)
{
System.out.println ("ASS");
}
return pic;
}
/**
* This method finds the angle between two different sets of coordinates.
*
* @param x1 The 1st x-coordinate.
* y1 The 1st y-coordinate.
* x2 The 2nd x-coordinate.
* y2 The 2nd y-coordinate.
* @return The angle between the two sets of coordinates.
*/
public double findAngle (double x1, double y1, double x2, double y2)
{
double ang = 0, slope;
if (x2 != x1)
slope = (y2 - y1) / (x2 - x1);
else
slope = 999999999;
//ang = arctand (slope);
if (slope > 0)
{
if (y2 < y1)
{
ang = 180 + ang;
}
}
else if (slope < 0)
{
if (x2 < x1)
ang = 180 + ang;
if (x2 > x1)
ang = 360 + ang;
}
else
{
if (x2 > x1)
ang = 0;
if (x2 < x1)
ang = 180;
}
return ang;
}
public void stop ()
{
try
{
Thread.sleep (1000);
}
catch (Exception e)
{}
}
/**
* Controls the collision of the Curling Rocks.
* Based on the type of of collision, it will figure out the calculations that state where the new Rock shall go.
*
* @param rock1 This contains the initial rock that is hitting another rock.
* rock2 This is the rock, that is being hit.
*/
public void collide (Rock rock1, Rock rock2)
{
double temp1, temp2, temp3, nvx1, nvy1, nvx2, nvy2, magnitude, dirx, diry, mag1, mag2;
dirx = -(Math.abs (rock2.getVelocityX ()) / rock2.getVelocityX ()) * (Math.abs (rock1.getVelocityX ()) / rock1.getVelocityX ());
diry = -(Math.abs (rock2.getVelocityY ()) / rock2.getVelocityY ()) * (Math.abs (rock1.getVelocityY ()) / rock1.getVelocityY ());
mag1 = distance (0, 0, rock1.getVelocityX (), rock1.getVelocityY ());
mag2 = distance (0, 0, rock2.getVelocityX (), rock2.getVelocityY ());
temp1 = findAngle (rock1.getXPosition (), rock1.getYPosition (), rock2.getXPosition (), rock2.getYPosition ());
temp2 = findAngle (0, 0, rock2.getXPosition (), rock2.getVelocityY ()) - temp1;
temp3 = findAngle (0, 0, rock1.getXPosition (), rock1.getVelocityY ()) - temp1;
temp2 = findAngle (0, 0, Math.cos (temp2), -(Math.sin (temp2))) + temp1;
temp3 = findAngle (0, 0, Math.cos (temp3), -(Math.sin (temp3))) + temp1;
nvx1 = Math.cos (temp2); //acos?
nvy1 = Math.sin (temp2); //asin?
nvx2 = Math.cos (temp3);
nvy2 = Math.sin (temp3);
rock2.setXVelocity (-nvx1 * dirx * mag1);
rock2.setYVelocity (-nvy1 * diry * mag1);
rock1.setXVelocity (-nvx2 * mag2);
rock1.setYVelocity (-nvy2 * mag2);
rock1.setPosition ((int) (rock1.getXPosition () + rock1.getVelocityX () * 4), (int) (rock1.getYPosition () + rock1.getVelocityY () * 4));
rock2.setPosition ((int) (rock2.getXPosition () + rock2.getVelocityX () * 4), (int) (rock2.getYPosition () + rock2.getVelocityY () * 4));
}
public void firstChanges (Rock playingRock)
{
PlayArea game = new PlayArea (player1, player2);
add (game);
resizeRate = .7;
updateXCoord = 0;
updateYCoord = -4;
updateWidth = WIDTH;
updateHeight = HEIGHT;
view = "VIEW UPDATE";
game.gameView = "VIEW";
if (playingRock.getYPosition () < 265)
{
playingRock.setPosition ((int) playingRock.convertXPosition( playingRock.getXPosition ()), (int) ((HEIGHT) + playingRock.getHeight ()));
playingRock.setPicName ("New_" + player1.getRockColour ());
playingRock.setWidth (65);
playingRock.setHeight (60);
game.changeView ();
game.paintComponent (getGraphics ());
firstImage = false;
secondChanges (playingRock);
}
}
public void secondChanges (Rock playingRock)
{
System.out.println ("VIEW 2");
resizeRate = .2;
updateXCoord = 0;
updateYCoord = -3;
updateWidth = WIDTH;
updateHeight = HEIGHT;
view = "Second View Update";
}
public double convertXPosition (double xPosition)
{
double newAwayFromCentre = ((WIDTH/2) - xPosition) * 5.65;
return ((WIDTH/2) - newAwayFromCentre);
}
/**
* Launches the Curling Rock.
* This will also subtract the friction constant from the momentum for each loop, and will create a delay for the moving Rock.
* This will also detect if a collision occurs.
* After the Rock reaches specific y Coordinates it will change the background image, and the image of the rock.
*/
public void actualRunning ()
{
double xBoundry1 = (WIDTH/2) - 200, xBoundry2= (WIDTH/2) + 200;
double startLocation = currentRock.getYPosition ();
// currentRock.setXVelocity (UserInput.convertToXVelocity (UserInput.direction));
// currentRock.setYVelocity (UserInput.convertToYVelocity (UserInput.direction));
double cs, sc, v1;
// double momentumX = ((rocks [0].getVelocityX () * (rocks [0].MASS - FRICTION))/100);
// double momentumY = ((rocks [0].getVelocityY () * (rocks [0].MASS - FRICTION))/100);
int counter =0;
paintComponent (getGraphics ());
startClock ();
outer:
while (running)
{
// for (int i = 0 ; i < MAX_PARTICLES ; i++)
// {
// if (!isInBound (rocks [i], xBoundry1, xBoundry2))
// {
// break outer;
// }
double num = putDelay ();
if (Math.abs (currentRock.getYPosition () - startLocation) > 1)
{
//System.out.println (resizeRate);
currentRock.setWidth (currentRock.getWidth () - resizeRate);
currentRock.setHeight (currentRock.getHeight () - resizeRate);
startLocation = currentRock.getYPosition ();
xBoundry1 += 0.1;
xBoundry2 -= 0.1;
}
v1 = Math.sqrt (currentRock.getVelocityX () * currentRock.getVelocityX () + currentRock.getVelocityY () * currentRock.getVelocityY ());
if (v1 != 0.)
{
cs = currentRock.getVelocityX () / v1;
sc = currentRock.getVelocityY () / v1;
v1 -= 20. * num;
if (v1 < 0.)
{
currentRock.setXVelocity (0.);
currentRock.setYVelocity (0.);
running = false;
}
else
{
currentRock.setXVelocity (v1 * cs);
currentRock.setYVelocity (v1 * sc);
// System.out.println (v1 + " -X- " + cs);
// System.out.println (v1 + " -Y- " + sc);
}
}
System.out.println (currentRock.getXPosition ());
System.out.println (currentRock.getYPosition ());
currentRock.setPosition ((int) (currentRock.getXPosition () + (currentRock.getVelocityX () * num)), (int) (currentRock.getYPosition () + (currentRock.getVelocityY () * num)));
// if (momentumX < 0 || momentumY <0 || delay > 150)
// {
// momentumX = -(momentumX);
// momentumY = -(momentumY);
// System.out.println (delay + " MX: " + momentumX + " MY: " + momentumY);
// break outer;
//
// }
// else
// {
// if ( counter == 75)
// {
// counter = 0;
// if (momentumX != 0)
// {
// momentumX = (((momentumX * 100) - (FRICTION*1.5))/100);
// }
// if (momentumY != 0)
// {
// momentumY = (((momentumY * 100) - (FRICTION * 1.5))/100) ;
// }
// }
// }
// counter ++;
if (firstImage)
{
firstChanges (currentRock);
}
else
{
secondChanges (currentRock);
}
//ball collision
for (int i = 1; i < listOfRocks.size (); i++)
{
if (distance (currentRock.getXPosition () + (currentRock.getWidth ()/2), currentRock.getYPosition () + (currentRock.getHeight ()/2), listOfRocks.get (i).getXPosition ()+ (listOfRocks.get (i).getWidth ()/2), listOfRocks.get (i).getYPosition ()+ (listOfRocks.get (i).getHeight ()/2)) <= 50 && !currentRock.getCh () && !listOfRocks.get (i).getCh ())
{
System.out.println ("It Went Here");
collide (currentRock, listOfRocks.get (i));
}
}
//wall collision
// if (rocks [i].getXPosition () >= 690 && rocks [i].getVelocityX () > 0)
// {
// rocks [i].setXVelocity (-rocks [i].getVelocityX ());
// }
// if (rocks [i].getXPosition () <= 10 && rocks [i].getVelocityX () < 0)
// {
// rocks [i].setXVelocity (-rocks [i].getVelocityX ());
// }
//
// if (rocks [i].getYPosition () >= 340 && rocks [i].getVelocityY () > 0)
// {
// rocks [i].setYVelocity (-rocks [i].getVelocityY ());
// }
//
// if (rocks [i].getYPosition () <= 10 && rocks [i].getVelocityY () < 0)
// {
// rocks [i].setYVelocity (-rocks [i].getVelocityY ());
// }
// delay += FRICTION *2;
// try
// {
// Thread.sleep ((int) delay);
// }
// catch (Exception e)
// {
// }
paintComponent (getGraphics ());
}
stop ();
convertToMainView (currentRock);
//paintComponent (getGraphics ());
}
public void convertToMainView (Rock rock)
{
double awayFromMiddle = (RockMotionReal.WIDTH/2 -(((RockMotionReal.WIDTH/2) - rock.getXPosition ())/5.65));
rock.setPosition ((int) awayFromMiddle, (int) rock.getYPosition ());
rock.setPicName ("Rock_" + player1.getRockColour ());
System.out.println (rock.getYPosition ());
double minimizeRate = Math.abs ((rock.getYPosition () - (WIDTH/2 - 15))* 0.7);
System.out.println (minimizeRate);
rock.setWidth (minimizeRate - 50);
rock.setHeight (minimizeRate - 45);
}
public boolean isInBound (Rock rock,double xBoundry1,double xBoundry2)
{
System.out.println ("Is in Bound");
if (rock.getXPosition () > xBoundry1 && rock.getXPosition () < (xBoundry2- rock.getWidth ()))
{
System.out.println ("meets the criteria");
return true;
}
return false;
}
}
In this class, the paintComponent (Graphics g) is beign called but it is not updating to the screen.
the class, in wich i add the RockMotionReal is this one:
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class PlayArea extends JPanel implements MouseListener, MouseMotionListener
{
private final int WIDTH=300, HEIGHT=300;
private DecimalFormat fmt;
private Point current;
private int centerX, centerY;
private double length;
private Rock playingRock;
private RockMotionReal t;
public String gameView;
Point point1 = null, point2 = null;
double startPointX;
double startPointY;
double endPointX;
double endPointY;
boolean valid = true;
public static double xSubtract;
public static double ySubtract;
public static double xPoint;
public static double yPoint;
public UserInput ui;
private boolean everythingLoaded = false;
public Player player1;
public Player player2;
// GameDial dial = new GameDial ();
//-----------------------------------------------------------------
// Constructor: Sets up the panel and necessary data.
//-----------------------------------------------------------------
public PlayArea(Player player1, Player player2)
{
super ();
addMouseListener (this);
Dimension screenSize = Toolkit.getDefaultToolkit ().getScreenSize (); //gets the size of the screen
setPreferredSize (new Dimension(RockMotionReal.WIDTH, RockMotionReal.HEIGHT));
addMouseListener (this);
ui = new UserInput (player1, player2);
gameView = "VIEW";
everythingLoaded = true;
this.player1 = player1;
this.player2 = player2;
}
public void startGame ()
{
if (everythingLoaded)
{
RockMotionReal motion = ui.execute ();
System.out.println ("Got here first");
add (motion);
repaint ();
motion.actualRunning ();
gameView = "VIEW";
}
}
//-----------------------------------------------------------------
// Draws a line from the mouse pointer to the center point of
// the applet and displays the distance.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
if (page == null)
{
System.out.println ("It is NULL HERE");
}
//playingRock = t.getRock ();
//super.paintComponent (page);
Image background = loadImage ("K:\\JAVA_FINAL_ISP\\Resources\\JAVA_ISP_ROCKS\\" +gameView + ".png");
//Dimension screenSize = Toolkit.getDefaultToolkit ().getScreenSize (); //gets the size of the screen
page.drawImage (background, 0, 0, RockMotionReal.WIDTH, RockMotionReal.HEIGHT, null);
// if (point1 != null && point2 != null)
// page.drawLine (point1.x, point1.y, point2.x, point2.y);
}
public void changeView ()
{
gameView = "Second View";
}
/**
*Returns the Image that is found at the given location of the picture.
*
*@param picLocation The location of the image that is required to be loaded.
*@return The Image at the specific location.
*/
public Image loadImage (String picLocation) //Loads the picture needed
{
Image pic = Toolkit.getDefaultToolkit ().getImage (picLocation);
MediaTracker tracker = new MediaTracker (new Frame ());
tracker.addImage (pic, 0);
try
{
tracker.waitForAll ();
}
catch (InterruptedException e)
{
//System.out.println ("ASS");
}
return pic;
}
public void mousePressed (MouseEvent event)
{
if (ui.isDirectionLocked () && !ui.isPowerLocked ())
{
ui.stopPower ();
}
if (!ui.isDirectionLocked ())
{
ui.stopDirection ();
}
// if (!ui.isDirectionLocked ())
// {
// ui.stopDirection ();
// }
//// if (dial.running)
//// {
//// System.out.println ("went in here");
//// if (!dial.directionLocked)
//// {
//// System.out.println ("DIRECTION" + dial.directionFixed ());
//// }
//// else
//// {
//// System.out.println ("POWER: " + dial.powerFixed ());
//// }
//// }
// RockMotionReal a = new RockMotionReal (player1.getThisPlayerRocks (), player2.getThisPlayerRocks (), player1, player2);
// add (a);
// a.actualRunning ();
}
//y=-0.25(x-centre of screen pt)^2+40
public void mouseReleased(MouseEvent event)
{
}
// if (!dial.directionLocked)
// {
// direction = dial.directionFixed ();
// }
// else
// {
// power = dial.powerFixed ();
// if (dial.directionLocked && dial.powerLevelLocked)
// {
// t.actualRunning ();
// }
// }
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
// point1 = event.getPoint();
//
// System.out.println ("Clicked :D");
// valid = true;
// startPointX = (int) point1.getX ();
// startPointY = (int) poigetY ();
}
//y=-0.25(x-centre of screen pt)^2+40
public void mouseMoved (MouseEvent event) {
point2=event.getPoint();
xPoint=point2.getX();
if (xPoint<100 &&xPoint >700)
yPoint=-0.25*Math.pow(xPoint-500,2)+100;//change 500 to have the thing in the cntre and 100 to change the beight of parabola
}
public void birdEye ()
{
}
public void mouseDragged (MouseEvent event) {}
}
i know this is alot of code, but if anyone can help, it will be greatly appreciated :D