Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Problem with getWidth() and getHeight()

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem with getWidth() and getHeight()

    I am taking a java course and I have an assignment of creating the hangman game with involves a console and gcanvas class. THe console part works, but I am having a problem with the gcanvas implementation. I have all my graphic objects created, and just needs to be called at the proper time. I just wanted to initially test to make sure that my graphics were aligned where I wanted them to be.

    I basically want my graphic objects to be referenced from the centerX and centerY of the canvas.

    THe problem is when I run the code as is, just to test the graphics positions, it looks like the getWidth and getHeight inside the HangmanCanvas class is being set to 0, 0.

    Is there something that I am not seeing when I am initializing it?

    THanks

    Hangman.java CODE --> main code that runs the program

    /*
     * File: Hangman.java
     * ------------------
     * This program will eventually play the Hangman game from
     * Assignment #4.
     */
     
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
     
    import java.awt.*;
     
    public class Hangman extends ConsoleProgram {
     
    private static final int NUMBER_OF_GUESSES = 8;
    private static final String DASH = "-";
    private RandomGenerator rgen = RandomGenerator.getInstance();
     
    private HangmanLexicon hangLexicon;
    private HangmanCanvas hangCanvas;
    private String hiddenWord;
    private String displayWord;
    private int guessRemaining = NUMBER_OF_GUESSES;
    private boolean wordFound = false;
     
    	public void init()
    	{
    		hangCanvas = new HangmanCanvas();
    		add(hangCanvas);
     
    	}
     
    	public void run() 
    	{
    		println("Welcome to Hangman!");
     
    		GenerateWord();
     
    		hangCanvas.test();
     
    		String input;
    		char userInput;
     
        	while((!wordFound) || (guessRemaining != 0))
        	{
     
        		println("The word now looks like this: " + hiddenWord);
        		println("                              " + displayWord);
     
        		println("You have " + guessRemaining + " guesses left.\n");
     
        		input = readLine("Your guess: ");
        		userInput = input.charAt(0); 
     
            	while(!Character.isLetter(userInput))
            	{
            		println("\nNOT A VALID LETTER, PLEASE ENTER AGAIN \n");
        			input = readLine("Your guess: ");
        			userInput = input.charAt(0); 
            	}
     
            	CompareInputToWord(userInput);
            	CheckGameStatus();
     
        	}
     
     
     
    	}
     
    	private void GenerateWord()
    	{
    		/* Concatenates empty hiddenWord with the random word */
     
    		hangLexicon = new HangmanLexicon();
    		displayWord = hangLexicon.getWord(rgen.nextInt(0,9));
     
    		hiddenWord = ConcatNCopies(displayWord.length(), DASH);
     
    	}
     
    	private String ConcatNCopies(int n, String str)
    	{
    		String result = "";
    		for(int i=0; i<n; i++)
    		{
    			result += str;
    		}
     
    		return result;
    	}
     
    	private void CompareInputToWord(char userInput)
    	{
    		userInput = Character.toUpperCase(userInput);
    		int index = 0;
     
    		index = displayWord.indexOf(userInput, index);
     
    		/* If the userInput letter was not found in the word */
    		if(index == -1)
    		{
    			println("There are no " + userInput + "\'s in the word. ");
    			guessRemaining--;
    			return;
    		}
     
    		while(index != -1)
    		{
     
    			if(index == 0)		//If the input is the first letter of the word
    			{
    				hiddenWord = displayWord.charAt(index) + hiddenWord.substring(index + 1);
    				index++;
    			}
    			else
    			{
    				hiddenWord = hiddenWord.substring(0, index) + displayWord.charAt(index) + hiddenWord.substring(index + 1);
    				index++;
    			}
     
    			index = displayWord.indexOf(userInput,index);
    		}
     
    		println("That guess is correct.");
     
    	}
     
    	private void CheckGameStatus()
    	{
    		if(hiddenWord.equals(displayWord))				//If the user found the word
    		{
    			wordFound = true;					
    			guessRemaining = 0;							//Must set to 0 to break out of main while loop
     
    			println("You guessed the word: " + hiddenWord);
    			println("YOU WIN!");
    		}
    		else if(guessRemaining == 0)
        	{
    			wordFound = true;							//Must set to true to break out of main while loop
        		println("\nYou're completely hung!");
        		println("The word was: " + displayWord);
        		println("YOU LOSE!");
        	}
    	}
     
     
    }


    HangmanCanvas.java CODE --> where the graphics are initialized

    /*
     * File: HangmanCanvas.java
     * ------------------------
     * This file keeps track of the Hangman display.
     */
     
    import java.awt.Color;
     
    import acm.graphics.*;
     
    public class HangmanCanvas extends GCanvas {
     
    	private double centerX = getWidth()/2;
    	private double centerY = getHeight()/2;	
    	private static final int GAP = 100;
    	private static String DISPLAY_FONT = "SansSerif-20";
     
    /** Resets the display so that only the scaffold appears */
    	public void test() {
    	//	removeAll();
     
    		DrawScaffold();
    		DrawLeftArm();
    		DrawRightArm();
    		DrawHead();
    		DrawBody();
    		DrawRightLeg();
    		DrawLeftLeg();
     
    		displayWord("HEHEHEHEHEHEHEHEHEH");  
     
    	}
     
     
    /**
     * Updates the word on the screen to correspond to the current
     * state of the game.  The argument string shows what letters have
     * been guessed so far; unguessed letters are indicated by hyphens.
     */
    	public void displayWord(String word) {
     
    		GLabel displayWord = new GLabel(word);
    		displayWord.setFont(DISPLAY_FONT);
    		displayWord.setLocation(centerX, centerY);
     
    		add(displayWord);
    	}
     
    /**
     * Updates the display to correspond to an incorrect guess by the
     * user.  Calling this method causes the next body part to appear
     * on the scaffold and adds the letter to the list of incorrect
     * guesses that appears at the bottom of the window.
     */
    	public void noteIncorrectGuess(char letter) {
    		/* You fill this in */
    	}
     
     
    	private void DrawScaffold()
    	{		
    		double scaffoldHeight = centerY - (BODY_LENGTH/2) - (2*HEAD_RADIUS) - ROPE_LENGTH;
    		double scaffBeamConnX = centerX - BEAM_LENGTH;
     
    		GLine scaffold = new GLine(scaffBeamConnX, scaffoldHeight, scaffBeamConnX, scaffoldHeight + SCAFFOLD_HEIGHT);
    		GLine beam = new GLine(scaffBeamConnX, scaffoldHeight, centerX, scaffoldHeight);
    		GLine rope = new GLine(centerX, scaffoldHeight, centerX, scaffoldHeight + ROPE_LENGTH);
    		GRect base = new GRect(scaffBeamConnX - BASE_OFFSET, scaffoldHeight + SCAFFOLD_HEIGHT, BASE_WIDTH, BASE_HEIGHT);
     
    		base.setFillColor(Color.BLACK);
    		base.setFilled(true);
     
    		add(scaffold);
    		add(beam);
    		add(rope);
    		add(base);
    	}
     
    	private void DrawHead()
    	{
    		double scaffoldHeight = centerY - (BODY_LENGTH/2) - (2*HEAD_RADIUS) - ROPE_LENGTH;
     
    		GOval head = new GOval(centerX - HEAD_RADIUS, scaffoldHeight + ROPE_LENGTH, 2*HEAD_RADIUS, 2*HEAD_RADIUS);
    		add(head);
    	}
     
    	private void DrawBody()
    	{
    		GLine body = new GLine(centerX, centerY - BODY_LENGTH/2, centerX, centerY + BODY_LENGTH/2);
    		add(body);
    	}
     
    	private void DrawLeftArm()
    	{
    		double armHeightY = centerY - BODY_LENGTH/2 + ARM_OFFSET_FROM_HEAD;
    		double elbowJointX = centerX - UPPER_ARM_LENGTH;
     
    		GLine leftArm = new GLine(centerX, armHeightY, elbowJointX, armHeightY);
    		GLine leftHand = new GLine(elbowJointX, armHeightY, elbowJointX, armHeightY + LOWER_ARM_LENGTH);
    		add(leftArm);
    		add(leftHand);
    	}
     
    	private void DrawRightArm()
    	{
    		double armHeightY = centerY - BODY_LENGTH/2 + ARM_OFFSET_FROM_HEAD;
    		double elbowJointX = centerX + UPPER_ARM_LENGTH;
     
    		GLine rightArm = new GLine(centerX, armHeightY, elbowJointX, armHeightY);
    		GLine rightHand = new GLine(elbowJointX, armHeightY, elbowJointX, armHeightY + LOWER_ARM_LENGTH);
    		add(rightArm);
    		add(rightHand);
    	}
     
    	private void DrawLeftLeg()
    	{
    		double legHeightY = centerY + BODY_LENGTH/4;
    		double hipJointX = centerX - HIP_WIDTH/4;
    		double footJointY = legHeightY + LEG_LENGTH;
     
    		GLine leftHip = new GLine(centerX, legHeightY, hipJointX, legHeightY);
    		GLine leftLeg = new GLine(hipJointX, legHeightY, hipJointX, legHeightY + LEG_LENGTH);
    		GLine leftFoot = new GLine(hipJointX, footJointY, hipJointX - FOOT_LENGTH, footJointY);
     
    		add(leftHip);
    		add(leftLeg);
    		add(leftFoot);
    	}
     
    	private void DrawRightLeg()
    	{
    		double legHeightY = centerY + BODY_LENGTH/2;
    		double hipJointX = centerX + HIP_WIDTH/2;
    		double footJointY = legHeightY + LEG_LENGTH;
     
    		GLine rightHip = new GLine(centerX, legHeightY, hipJointX, legHeightY);
    		GLine rightLeg = new GLine(hipJointX, legHeightY, hipJointX, legHeightY + LEG_LENGTH);
    		GLine rightFoot = new GLine(hipJointX, footJointY, hipJointX + FOOT_LENGTH, footJointY);
     
    		add(rightHip);
    		add(rightLeg);
    		add(rightFoot);
    	}
     
     
    	private static final int BASE_OFFSET = 40;
    	private static final int BASE_WIDTH = 250;
    	private static final int BASE_HEIGHT = 50;
     
    /* Constants for the simple version of the picture (in pixels) */
    	private static final int SCAFFOLD_HEIGHT = 360;
    	private static final int BEAM_LENGTH = 144;
    	private static final int ROPE_LENGTH = 18;
    	private static final int HEAD_RADIUS = 36;
    	private static final int BODY_LENGTH = 144;
    	private static final int ARM_OFFSET_FROM_HEAD = 28;
    	private static final int UPPER_ARM_LENGTH = 72;
    	private static final int LOWER_ARM_LENGTH = 44;
    	private static final int HIP_WIDTH = 36;
    	private static final int LEG_LENGTH = 108;
    	private static final int FOOT_LENGTH = 28;
     
    }


  2. #2
    Member
    Join Date
    Oct 2011
    Posts
    50
    My Mood
    Fine
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Problem with getWidth() and getHeight()

    I don't see where you set-up your canvas in order to get width and height. Basically you call the method on a empty canvas. A solution would be to first give it's dimension, or use the method calls later, after you did the former.

    application context
    Last edited by daniel.j2ee; December 13th, 2011 at 04:58 PM.

  3. #3
    Junior Member
    Join Date
    Oct 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with getWidth() and getHeight()

    I'm not quite sure I understand what you mean.

    I created a new variable hangCanvas of class HangmanCanvas and added(hangCanvas), which are inside the init method of the hangman class...Then in the run method, I put hangCanvas.test(), which test method is in the canvas class that draws all my graphic objects on to the screen.

    centerX and centerY for the graphic objects are initialized as instance variables with values of getWidth()/2, and getHeight()/2...

    Any suggestions?

  4. #4
    Junior Member
    Join Date
    Oct 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with getWidth() and getHeight()

    anyone can help me out?

  5. #5
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Problem with getWidth() and getHeight()

    What is add()? What are you trying to do with so many add() calls??? Is your program compiling?

  6. #6
    Junior Member
    Join Date
    Oct 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with getWidth() and getHeight()

    yeah my program compiles fine...

    the add()'s within the HangmanCanvas class are how I add the graphic objects to the screen. So every time a user inputs the a letter that is not in the "secret" word, then a new body part will display (aka hangman game)

  7. #7
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Problem with getWidth() and getHeight()

    Well, it seems that you are adding hangCanvas into nothing.

Similar Threads

  1. Replies: 3
    Last Post: January 5th, 2012, 01:44 AM