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 19 of 19

Thread: It works!!! eureka!!! Java...Day 12.

  1. #1
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default It works!!! eureka!!! Java...Day 12.

    So vector math works in java, but for some reason random does not work inside of methods?!?!
    Also it slows down and then freezes after running for about 5 minutes, is there a way to clean out the memory periodically so that this does not happen? The QB version did not have this issue, but then it was running only 200 stars and in java I have 1250 stars going.

    Anyways, it works and looks beautiful, a big thanks to Norm, Junky, and Tjstretch. I was asked to upload working code, so here it is:

    make a new folder somewhere and name it StarScape.
    inside the StarScape folder make another new folder and name it Star.

    put StarScape.java and StarScape.html in the Starscape folder.
    put Star.java in the Star folder.

    open command prompt and navigate to the StarScape folder.
    at promt type javac StarScape.java Star/Star.java

    click on StarScape.html and enjoy!!!

    StarScape.html
    <html>
    	<head>
    		<title>StarScape Applet</title>
    	</head>
    	<body>
    		<h1 align=center>StarScape Applet By Jon Crawford</h1>
    		<center>
    			<applet name="StarScape" 
    				code="StarScape.class" 
    				width=800 
    				height=600>
    			</applet>
    		</center>
    	</body>
    </html>

    Applet StarScape.java, change the maxStars from 1250 to whatever your want. I tweaked it and on my computer and found that 1250 is just enough stars to slow it down to the point that you can actually see the effect. 1,000,000 works too...lol.
    // starscape.java
    // by Jon Crawford
    import Star.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.io.*;
    import java.math.*;
     
    public class StarScape extends JApplet 
    {
      final int maxStars = 1250;
      String key = "";
      String valid;
      int index;
      double myX;
      double myY;
      int myRadius;
      double myLayer;
      int rectX;
      int rectY;
      int rectXX;
      int rectYY;
      Star stars[] = new Star[maxStars+1];//make 100 star objects
     
      public void paint(Graphics g)
      {
        g.setColor(Color.black);
        g.fillRect(0,0,800,600);// make the background black
        for (index = 0; index < maxStars; index++)
        {
          myX = Math.random() * 200 - 99;//star starts in a small square
          myY = Math.random() * 200 - 99;//in the center
          myLayer = Math.random() * 3;//random layer
          stars[index] = new Star();//fill array with stars
        }//end for 
        do
        {
          for (index = 0; index < maxStars; index++) 
          {
            myX = stars[index].getStarX();
            myY = stars[index].getStarY();
            myRadius = stars[index].getStarRadius();//get data for star at index number
            rectX = (int)(myX) - myRadius + 399;//myX and myY are based on a 0,0 in the center grid
            rectY = (int)(myY) - myRadius + 299;//as well as converting to a 0,0 at top left grid
            rectXX = myRadius * 2;//these lines setup the boundaries of
            rectYY = myRadius * 2;//a rectangular star
            g.setColor(Color.black);
            g.fillOval(rectX, rectY, rectXX, rectYY);//erase old star
            stars[index].moveStar();//move the star
            stars[index].starValid();
            valid = stars[index].getValid();//is the star out of bounds?
            if (valid == "false")
            {//is star out of bounds?
              myX = Math.random() * 200 - 99;//set new starting position
              myY = Math.random() * 200 - 99;
              myLayer = Math.random() * 3;//new random layer
              stars[index].resetStar(myX, myY, myLayer);
            }  
            myX = stars[index].getStarX();
            myY = stars[index].getStarY();
            myRadius = stars[index].getStarRadius();//get data agian because star was moved
            myLayer = stars[index].getStarLayer();//layer just denotes shade of star. 
            if (myLayer == 3) 
            {
              g.setColor(Color.white);
            }else if (myLayer == 2) 
            {
              g.setColor(Color.lightGray);
            }else if (myLayer == 1) 
            {
              g.setColor(Color.darkGray);
            }else 
            {
              g.setColor(Color.white);//these set color based on layer
            }
            rectX = (int)(myX) - myRadius + 399;
            rectY = (int)(myY) - myRadius + 299;
            rectXX = myRadius * 2;
            rectYY = myRadius * 2;//set up the new star I mean rectangle
            g.fillOval(rectX, rectY, rectXX, rectYY);//draw star
          }//end for
        }while (key == "");//should implement key listener
      }//end paint
    }//end starscape

    class Star.java
    // star.java
    // by Jon Crawford
    package Star;
     
    import java.util.*;
    import java.math.*;
     
    public class Star {
     
      private final int starSpeed = 1;
      private final int starRadius = 1;
      private final int starSteps = 0;
      private final float[] invalidValues = new float[]{ -399f, -299f, 399f, 299f, 0f, 0f};
      private String isValid = "false";
      private double starAngle;
      private double starField[] = new double[9];
     
      public void Star(double myX, double myY, double myLayer)
      {
        starAngle = (Math.sqrt((myX * myX)+(myY * myY)));//calculate the hypotenuse
        starField[0] = myX;//set data to star's arrary
        starField[1] = myY;//this is for current position
        starField[2] = myX / starAngle * starSpeed;//these set the next position
        starField[3] = myY / starAngle * starSpeed;//this is reltive current position
        starField[4] = myLayer;//back, mid, or foreground layer
        starField[5] = starRadius;//star starting size
        starField[6] = starSpeed * myLayer;//the starting speed
        starField[7] = starSteps;//star has taken 0 steps, every 5 steps star grows and speeds up
        starField[8] = starAngle;//store the hypotenuse
      }//end constructor
     
      public void moveStar() 
      {//mutator method
        System.out.println("") ;    
        starField[0] = starField[0] + starField[2];//next position becomes the curent position 
        starField[1] = starField[1] + starField[3];       
        starField[2] = starField[0] / starField[8] * starField[6];//new next position
        starField[3] = starField[1] / starField[8] * starField[6];
        starField[7] = starField[7] + 1;//increment steps
        if (starField[7] / 5 == (int)(starField[7] / 5) && starField[5] < 20)
        {//if star has taken 5 steps
          starField[5] = starField[5] + 1;//increment size
          starField[6] = starField[6] + 1;//increment speed
        }//end if      
      }//end moveStar
     
      public void resetStar(double myX, double myY, double myLayer)
      {//resetStar method
        starAngle = (Math.sqrt((myX * myX)+(myY * myY)));//calculate new hypotenuse
        starField[0] = myX;//set data to star's array
        starField[1] = myY;//same as default constructor
        starField[2] = myX / starAngle * starSpeed;
        starField[3] = myY / starAngle * starSpeed;
        starField[4] = myLayer;
        starField[5] = starRadius;
        starField[6] = starSpeed * myLayer;
        starField[7] = starSteps;
        starField[8] = starAngle;
      }//end resetStar
     
      public void starValid()
      {//isValid method
        if(starField[0] > invalidValues[0] && starField[1] > invalidValues[1] && starField[0] < 
     
    invalidValues[2] && starField[1] < invalidValues[3])
        {//in bounds?
          isValid = "true";
        }else
        {//out of bounds
          isValid = "false";
        }//end if
      }//end is valid
     
      public int getStarX() 
      {//get method
        return (int)(Math.round(starField[0]));
      }//end getStarX
     
      public int getStarY() 
      {//get method
        return (int)(Math.round(starField[1]));
      }//end getStarY
     
      public int getStarRadius() 
      {//get method
        return (int)(Math.round(starField[5]));
      }//end getStarRadius
     
      public int getStarLayer() 
      {//get method
        return (int)(Math.round(starField[4]));
      }//end getStarLayer
      public String getValid()
      {//get method
        return isValid;
      }//end isValid
     
    }//end class star


    TODO: add a stop button to click on to stop the animation. I have not got that far in my java book....
    TODO: make this as the background on my webpage, with buttons and text on top of it.
    Last edited by Spidey1980; August 18th, 2011 at 01:01 PM. Reason: add highlight


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: It works!!! eureka!!! Java...Day 12.

    Thanks for posting the code you got working.
    Also it slows down and then freezes after running for about 5 minutes, is there a way to clean out the memory periodically so that this does not happen? The QB version did not have this issue, but then it was running only 200 stars and in java I have 1250 stars going.
    A few points. If you are trying to perform animation, it should not be done within the paint method. Use a Timer (see How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features) ) or a thread which calls repaint() every time a new paint is needed, otherwise you get stuck within the paint method and will never exit (which is not a behavior you want). Second, when checking for string equality, use the equals method (eg while (key.equals(""))

  3. The Following User Says Thank You to copeg For This Useful Post:

    Spidey1980 (August 18th, 2011)

  4. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Some more points, isValid is a natural boolean
    vs being a String with a value of "false" etc

    Initialize the stars array outside of the paint method.

    Check the constructor(??) for the Star class. When is it called?

    Otherwise a nice visual effect.

  5. The Following User Says Thank You to Norm For This Useful Post:

    Spidey1980 (August 18th, 2011)

  6. #4
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Quote Originally Posted by copeg View Post
    a thread which calls repaint().......use the equals method (eg while (key.equals(""))
    Thank you I will try repaint().

    whenever I try .equals("") I get a class not found or .class expected error. If I were to get .equals("") to work, would it cause lees of a memory leak than ("" == "")?

    Quote Originally Posted by Norm View Post
    1)Some more points, isValid is a natural boolean
    vs being a String with a value of "false" etc

    2)Initialize the stars array outside of the paint method.

    2)Check the constructor(??) for the Star class. When is it called?

    3)Otherwise a nice visual effect.
    1)Tjstretch gave me an example of isValid being a boolean. He used a "sychronized public boolean" thing and when I copy and pasted the method, the compiler barfed all over me. So I just did it as a String and it worked.

    2)The Stars are initialized outside of paint, however to shorten things I filled the Stars array with data (called the constructor) inside a for...loop within the main/applet class, just before the paint method starts. I realize it would be more proper to have a separate method out side of my main/applet method for this.

    3)Thank you for the compliment, I really means a lot!
    Last edited by Spidey1980; August 18th, 2011 at 11:49 AM.

  7. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    I get a class not found or .class expected error.
    Please post the full text of the error message.

    For this test: .equals("") look also at other methods in the String class: length and isEmpty

  8. The Following User Says Thank You to Norm For This Useful Post:

    Spidey1980 (August 18th, 2011)

  9. #6
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    String class? so I just forgot to "import java.string.*;".
    .length had not been working either; just forgot the import.

    For now I'm done until I continue my adventure through my java for beginners book. I still have buttons and panels to learn; as well as more complicated .class trees.

  10. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    No there is no problem with an import statement.
    This statement is wrong:
    import java.string.*
    There is no java.string package.

    Please copy and paste here the full text of the error message. Without your posting that there is no way to make any suggestions.

  11. The Following User Says Thank You to Norm For This Useful Post:

    Spidey1980 (August 18th, 2011)

  12. #8
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Ok you got me curious. just changed "....index = 0; index< maxStars +1;...." to "....;index < stars.length;....." and it worked. So I was probably misspelling "length" before, or else I was trying "stars[].length". Now to try ".equals()"....

    note: after looking that up, you are correct. the String class is in "java.io.*"; which I was already importing.

    Will this help me with the memory leak, or is it just proper form?
    Last edited by Spidey1980; August 18th, 2011 at 12:35 PM.

  13. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    the String class is in "java.io.*";
    Where did you see that? That is wrong.
    The package for a class when you look at the API doc is just above the name of the class at the top of the page in smaller letters.

  14. #10
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    I googled "java .length" and the first result was:
    Java Length Method, Find Length of String Java, Length Method in Java

    The code there starts with "import java.io.*;" is it for the bufferedreader?

  15. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Yes BufferedReader is in the java.io package.

    Here is a link for the API doc. Save it. I use it many times an hour.
    Java Platform SE 6

  16. The Following User Says Thank You to Norm For This Useful Post:

    Spidey1980 (August 18th, 2011)

  17. #12
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Then I'm probably not even using half my imports. This is more than likely increasing my compiled file size and lending to the memory leak I am experiencing.

  18. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    import statements have NOTHING to do with the size of the generated code. They are used by the compiler to find classes that you are using. Extra statements will only make the source file larger. They have NO effect on the size of the output file.
    You do not need to use import statements. You can code the full path to any class in you code:
    java.io.BufferedReader br = new java.io.BufferedReader(....
    The import statements allows you to leave off the package path: java.io

  19. #14
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    This is more than likely increasing my compiled file size and lending to the memory leak I am experiencing.
    It's absolutely impossible. The import statements are only in your code to help the compiler resolve name space collisions. They're used by the compiler to select which packages to search for names of classes it doesn't recognise in your code. They have no effect at all on the quantity of code output.

    I have to confess to looking at your system-crippling applet with jconsole and VisualVM and couldn't see anything obviously wrong with the number of live objects. I'm wondering if it's some drawing weirdness caused by you looping around inside the paint method and never exiting it.

  20. #15
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: It works!!! eureka!!! Java...Day 12.

    I'm wondering if it's some drawing weirdness caused by you looping around inside the paint method and never exiting it.
    This is exactly the problem.

    As for the string equals, if you receive errors post the code (preferably as an SSCCE). String is a member of the java.lang package, which is a default import. You call equals on a string object - using == checks for object equality

  21. #16
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Well, with QB when I used "include" (same as "import") it compiled the whole included library (class) into my code, making a stand alone executable. I guess java is different, the class stays where it is at to be called by the compiled code, not included in it.

    Quote Originally Posted by Sean4u View Post
    looping around inside the paint method and never exiting it.
    Yeah I gotta add some repaints() or something. When a star get's reused (starts again in center) artifacts are being left in the memory, which adds up.

    Right now it is about as bad as the code inside my Dish Network receiver (it completely freezes every couple of days, needing a complete reboot, even sooner when going trough a menu list and loading the info for about 200 movies. Nothing can be done but for Dish to completely overhaul the code, fat chance of that...)

    Quote Originally Posted by copeg View Post
    As for the string equals, if you receive errors post the code (preferably as an SSCCE). String is a member of the java.lang package, which is a default import. You call equals on a string object - using == checks for object equality
    I was just misspelling it. Also, all but one comparison is on double types, not String types. The one String I'm comparing should be a Boolean.

    TODO: learn how to make a SSCCE.
    Last edited by Spidey1980; August 18th, 2011 at 01:20 PM.

  22. #17
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    using == checks for object equality
    Using == checks for built-in type equality or reference equality. String is sometimes confusing because of string interning: "hello" == "hello" is true when it ought to be false because it looks as though you're creating two new objects which happen to have identical contents, but that's not how Java works ... for java.lang.String.

  23. #18
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: It works!!! eureka!!! Java...Day 12.

    Quote Originally Posted by Sean4u View Post
    Using == checks for built-in type equality or reference equality. String is sometimes confusing because of string interning: "hello" == "hello" is true when it ought to be false because it looks as though you're creating two new objects which happen to have identical contents, but that's not how Java works ... for java.lang.String.
    Indeed. I should have been more clear...thanks for the clarification

  24. #19
    Member
    Join Date
    Aug 2011
    Posts
    86
    My Mood
    Lurking
    Thanks
    16
    Thanked 4 Times in 4 Posts

    Default Re: It works!!! eureka!!! Java...Day 12.

    Quote Originally Posted by Sean4u View Post
    I have to confess to looking at your system-crippling applet with jconsole and VisualVM and couldn't see anything obviously wrong with the number of live objects. I'm wondering if it's some drawing weirdness caused by you looping around inside the paint method and never exiting it.
    LOL check this...no wonder!Animation in Java applets - JavaWorld

Similar Threads

  1. GUI Only Works Sometimes
    By bgd223 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 12th, 2011, 08:08 AM
  2. jar file works on XP but not on Linux
    By cl2606 in forum Java Theory & Questions
    Replies: 1
    Last Post: June 10th, 2011, 09:19 AM
  3. This program works but Want to improve
    By SHStudent21 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 8th, 2011, 05:53 PM
  4. [SOLVED] Can someone verify if this code for deleting a BST works?
    By scottb80 in forum Java Theory & Questions
    Replies: 2
    Last Post: November 2nd, 2010, 10:19 AM
  5. How overloaded paint() works?
    By maikeru in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 21st, 2009, 06:13 PM