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

Thread: My java homework (very simple stuff)

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default My java homework (very simple stuff)

    Okay, so programming was never my strong side, but I have to get it done for next tuesday.

    So the idea behind my program is:

    There is a class for drawing a square, then there is the ship class that extends the square (assembles 5 of them into a ship)

    and theres the one that i've got a problem with. A fleet of ships which is basically a set of 2 or more ships (sets of 5 squares) that can move together.

    My code:

    Square:
    package assignment1;
     
    import java.awt.*;
     
    public class Square  
    {   
       private double x,y;    
     
       public Color color;    
     
       private int side;
     
       public Square()
       {
          x = 100;
          y = 100;
          side = 5;
    	  color = Color.orange;
       }
     
     
       public void draw(Graphics g) 
       {
          g.setColor(color);
          g.fillRect( (int)(x), (int)(y), (int)(2*side), (int)(2*side) );
       }
     
       public void setSide(int s)
       {
           side = s;
       }
     
       public int getSide()
       {
           return side;
       }
     
       public int getX()
       {
            return (int) x;
       }
     
       public int getY()
       {
            return (int) y;
       }
     
       public void setX(int xIn)
       {
           x = xIn;
       }
     
       public void setY(int setY)
       {
           y = setY;
       }
    }

    Ship:

    package assignment1;
     
    import java.awt.*;
     
    public class Ship extends Square  
    {   
     
     
        public Ship()
        {
            super();
        }
     
       public void draw(Graphics g) 
       {
          int side = super.getSide();
          int x = super.getX();
          int y = super.getY();
     
          g.setColor(color);
          g.fillRect( (int)(x), (int)(y), (int)(2*side), (int)(2*side) );
     
          g.setColor(color);
          g.fillRect( (int)(x), (int)(y - (2*side)), (int)(2*side), (int)(2*side) );
     
          g.setColor(color);
          g.fillRect( (int)(x - (2*side)), (int)(y - (2*side)), (int)(2*side), (int)(2*side) );
     
          g.setColor(color);
          g.fillRect( (int)(x + (2*side)), (int)(y - (2*side)), (int)(2*side), (int)(2*side) );
     
          g.setColor(color);
          g.fillRect( (int)(x), (int)(y - (4*side)), (int)(2*side), (int)(2*side) );
       }
     
    }

    And the FleetOfShips:

    package assignment1;
     
    import java.awt.*;
     
    public class FleetOfShips
    {
        Ship[] fleetMembers; 
        int total = 5; 
     
        FleetOfShips() 
        {
            fleetMembers = new Ship[total]; 
            for (int i = 0; i < total; i = i++) 
            {
                fleetMembers[i] = new Ship();  
                fleetMembers[i].setX (i * 10); 
                fleetMembers[i].setY (i * 10);
            }
        }
     
        public void draw(Graphics g)
        {
            for (int i = 0; i < total; i = i++)
            {
                fleetMembers[i].draw(g); 
            }
        }
     
        public void goSouth(int howFar)
        {
            for (int i = 0; i < total; i = i + 1) 
            {    
                fleetMembers[i].setY (fleetMembers[i].getY() + howFar); 
     
        }   
    } 
    }

    All of these 3 seem fine, they compile with no problems and first two work fine.

    How do I know that the square and the ship are fine? I use this piece of code to check if everything is working:

    package assignment1;
     
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*; 
     
    public class AnimateInTabSquare extends JApplet 
                        implements ActionListener, MouseListener, MouseMotionListener  
    {
     
        JPanel display;
        JTabbedPane tabpane;
        JEditorPane helpPane;
        Square mySquare;
     
        private int x;
        private int y;
     
        private Timer timer = new Timer(100,this);
     
        public AnimateInTabSquare() // constructor
        {
               display = new JPanel() 
               {
                    public void paintComponent(Graphics g) 
                    {
                        drawFrame(g);
                    }
                };
                //getContentPane().add(display);
        }
     
        public void init( ) 
        { 
            display.addMouseListener(this);
            display.addMouseMotionListener(this);
            timer.setDelay(10);
            timer.start();
     
            mySquare = new Square();
     
            tabpane = new JTabbedPane( ); 
     
            helpPane = new JEditorPane();
            // allow embedded html in your rendered text
            helpPane.setContentType( "text/html" );
            String helpText;
            helpText = "<html><body>line 1 of help<br>";
            helpText = helpText + "<em> another lne of help </em><br>";
            helpText = helpText + "last line of help</body></html>";
            helpPane.setText(helpText);
     
            // add tabs
            tabpane.addTab( "Game", display );
            tabpane.addTab( "Help", helpPane );
            // add tabbed pane to applet
            add( tabpane, BorderLayout.CENTER);
        }
     
        public void drawFrame(Graphics g) 
        {     
              // to compute and draw the next frame in the animation.          
              g.setColor(Color.black);  // fill the applet with a black background.
              g.fillRect(0, 0, getSize().width, getSize().height);
     
              // place here code that should happen every time that the timer makes the frame get re-drawn
              // Ask the myFleet object to draw itself.
              mySquare.draw(g);
        } // end drawFrame()
     
        // empty methods below must be here for mouseEventListener   
        public void mousePressed(MouseEvent evt) { }
        public void mouseDragged(MouseEvent evt) { }    
        public void mouseReleased(MouseEvent evt) { }   
        public void mouseMoved(MouseEvent evt) { } 
        public void mouseEntered(MouseEvent evt) { }
        public void mouseExited(MouseEvent evt) { }
     
        public void mouseClicked(MouseEvent evt) 
        { 
               if (mySquare.getSide() == 5)
                        mySquare.setSide(50);
                 else
                        mySquare.setSide(5); 
               display.repaint();
        }
     
        public void actionPerformed(ActionEvent evt) // triggered by timer
        {
                //display.repaint();
        }
    }

    This works perfectly fine for my "square" and "ship" classes, but unfortunately I am unable to make it work with the FleetOfShips class.

    Could anyone help me please?

    I really need to get this thing done.

    All I need is to get the fleet of ships (2 or more ships) to be drawn in an applet and react to a mouse click (move, change colour etc)

    I spent like my entire day trying to figure this out, but I can't :/


    @EDIT

    I am almost sure that the problem lies somewhere around this part:

        FleetOfShips() 
        {
            fleetMembers = new Ship[total]; 
            for (int i = 0; i < total; i = i++) 
            {
                fleetMembers[i] = new Ship();  
                fleetMembers[i].setX (i * 10); 
                fleetMembers[i].setY (i * 10);
            }
        }
    Last edited by macko939; April 23rd, 2014 at 10:07 PM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    This works perfectly fine for my "square" and "ship" classes, but unfortunately I am unable to make it work with the FleetOfShips class.
    Can you describe better what help you need? What does "unable to make it work" mean? Do you get errors, get unexpected results, don't get expected results, . . . ? Tell us how to duplicate your results and then describe how they should be different or what "working" (success) would be.
    All I need is to get the fleet of ships (2 or more ships) to be drawn in an applet and react to a mouse click (move, change colour etc)
    You kind of describe the object above, but how is it different for the or with the FleetOfShips class?

    Thinking out loud: A FleetOfShips objects must be multiple ship objects, so if an event (change color, turn, blink, etc.) happens to one of the ships in the fleet, then the same event should be applied to all in the same fleet. To accomplish that, put an action listener on all of the ship objects in the FleetOfShips so that an action on one causes the same change in all ship objects in the fleet.

  3. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My java homework (very simple stuff)

    Quote Originally Posted by GregBrannon View Post
    Can you describe better what help you need? What does "unable to make it work" mean? Do you get errors, get unexpected results, don't get expected results, . . . ? Tell us how to duplicate your results and then describe how they should be different or what "working" (success) would be.

    You kind of describe the object above, but how is it different for the or with the FleetOfShips class?

    Thinking out loud: A FleetOfShips objects must be multiple ship objects, so if an event (change color, turn, blink, etc.) happens to one of the ships in the fleet, then the same event should be applied to all in the same fleet. To accomplish that, put an action listener on all of the ship objects in the FleetOfShips so that an action on one causes the same change in all ship objects in the fleet.

    Okay so I use code the same as "AnimateInTabSquare" to make my fleet appear in the applet (to actually make it visible) but, unlike with my other classes, the applet window is white, doesn't show any error messages or anything and I have to use ctrl alt del to turn it off by killing process. It also compiles with no problems as well and I am really confused about this thing

    We're using blueJ at school

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    Hmmm. I don't see what you're seeing. I initially see a small orange square on a black background that changes to a big orange square on a black background when the applet is clicked, then alternates between the two squares on subsequent clicks.

    Are you seeing any errors in the console window (if BlueJ has such a thing - it must) when the applet is building or after you click on it?

  5. #5
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My java homework (very simple stuff)

    Quote Originally Posted by GregBrannon View Post
    Hmmm. I don't see what you're seeing. I initially see a small orange square on a black background that changes to a big orange square on a black background when the applet is clicked, then alternates between the two squares on subsequent clicks.

    Are you seeing any errors in the console window (if BlueJ has such a thing - it must) when the applet is building or after you click on it?
    Basically I got 3 classes.

    The first one is to draw an orange square on a black background that reacts to user actions (mouse clicks)

    The second one is a bunch of these squares drawn together to form a cross

    The third one (FleetOfShips) is basically the same principle, drawing 5 "ships" (sets of 5 squares) that can react to user actions



    The issue is, I just can't get the last one to display in applet, the applet crashes and gives me no error messages or anything. It compiles fine though.

  6. #6
    Member
    Join Date
    Dec 2013
    Location
    Honolulu
    Posts
    83
    Thanks
    1
    Thanked 4 Times in 2 Posts

    Default Re: My java homework (very simple stuff)

    java.awt.Canvas, and java.awt.Graphics, was the only ones I used on a file call ImageCanvas.java, ImageCanvas.class, java NetBean. Worked perfectly clear when debugging and compiling it on the NetBean, java. I wanted to point out that the difficult part for me was figuring out the static methods for the main class and the private class declared within the class. They all had the basic idea and codes, so I just copied and paste the original and changed the path files, Pictures/file.jpg. It was really difficult to see where the methods was going to be declared and how to write it or remember the same format the next time. Exceptions were caught and fixed. Happy for it. Exceptions are missing components of which the programmer must throw it or catch it, so as to respond to the computer's compiler. Very informative day in making 2 class files from NetBean, ImageCanvas.class and ImageCanvasA.class files were the 2 I made successfully through NetBean Java.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    The issue is, I just can't get the last one to display in applet, the applet crashes and gives me no error messages or anything. It compiles fine though.
    As I said, what you've posted does not exhibit the behavior you've described when I run it, though the FleetOfShips class is not used. Please post the code that demonstrates the behavior you've described. We can't help you fix code we can't see.

  8. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My java homework (very simple stuff)

    Quote Originally Posted by planetHollywood View Post
    java.awt.Canvas, and java.awt.Graphics, was the only ones I used on a file call ImageCanvas.java, ImageCanvas.class, java NetBean. Worked perfectly clear when debugging and compiling it on the NetBean, java. I wanted to point out that the difficult part for me was figuring out the static methods for the main class and the private class declared within the class. They all had the basic idea and codes, so I just copied and paste the original and changed the path files, Pictures/file.jpg. It was really difficult to see where the methods was going to be declared and how to write it or remember the same format the next time. Exceptions were caught and fixed. Happy for it. Exceptions are missing components of which the programmer must throw it or catch it, so as to respond to the computer's compiler. Very informative day in making 2 class files from NetBean, ImageCanvas.class and ImageCanvasA.class files were the 2 I made successfully through NetBean Java.
    I'm sorry mate but I have no idea what did you just said.

    @GregBrannon

    I am talking about the "FleetOfShips" class all the time here. That is the only one I got problem with.

    I dont know how to explain it, but basically we got 3 classes:

    Square
    Ship
    FleetOfShips

    which are used to draw simple shapes in applet. They're meant to inherit from each other (like square is the most basic one, a ship is a set of squares and the FleetOfShips is a set of ships)

    And our teacher gave us AnimateInTab*CLASS* class to test it (I gave you code for that in the first post as well).

    To test it I simply replace "Square" to "Ship" or "FleetOfShips" in the "AnimateInTabSquare" class. It works fine when I try to test "Square" and "Ship" classes, but it doesn't work when I try to test FleetOfShips.

    The simplest way to get that is to compile this:

    import java.awt.*;
     
    public class FleetOfShips
    {
        Ship[] fleetMembers; 
        int total = 5; 
     
        FleetOfShips() 
        {
            fleetMembers = new Ship[total]; 
            for (int i = 0; i < total; i = i++) 
            {
                fleetMembers[i] = new Ship();  
                fleetMembers[i].setX (i * 10); 
                fleetMembers[i].setY (i * 10);
            }
        }
     
        public void draw(Graphics g)
        {
            for (int i = 0; i < total; i = i++)
            {
                fleetMembers[i].draw(g); 
            }
        }
     
        public void goSouth(int howFar)
        {
            for (int i = 0; i < total; i = i + 1) 
            {    
                fleetMembers[i].setY (fleetMembers[i].getY() + howFar); 
     
        }   
    } 
    }

    and
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*; 
     
    public class AnimateInTabFleetOfShips extends JApplet 
                        implements ActionListener, MouseListener, MouseMotionListener  
    {
     
        JPanel display;
        JTabbedPane tabpane;
        JEditorPane helpPane;
        FleetOfShips myFleetOfShips;
     
        private int x;
        private int y;
     
        private Timer timer = new Timer(100,this);
     
        public AnimateInTabFleetOfShips() // constructor
        {
               display = new JPanel() 
               {
                    public void paintComponent(Graphics g) 
                    {
                        drawFrame(g);
                    }
                };
                //getContentPane().add(display);
        }
     
        public void init( ) 
        { 
            display.addMouseListener(this);
            display.addMouseMotionListener(this);
            timer.setDelay(10);
            timer.start();
     
            myFleetOfShips = new FleetOfShips();
     
            tabpane = new JTabbedPane( ); 
     
            helpPane = new JEditorPane();
            // allow embedded html in your rendered text
            helpPane.setContentType( "text/html" );
            String helpText;
            helpText = "<html><body>line 1 of help<br>";
            helpText = helpText + "<em> another lne of help </em><br>";
            helpText = helpText + "last line of help</body></html>";
            helpPane.setText(helpText);
     
            // add tabs
            tabpane.addTab( "Game", display );
            tabpane.addTab( "Help", helpPane );
            // add tabbed pane to applet
            add( tabpane, BorderLayout.CENTER);
        }
     
        public void drawFrame(Graphics g) 
        {     
              // to compute and draw the next frame in the animation.          
              g.setColor(Color.black);  // fill the applet with a black background.
              g.fillRect(0, 0, getSize().width, getSize().height);
     
              // place here code that should happen every time that the timer makes the frame get re-drawn
              // Ask the myFleet object to draw itself.
              myFleetOfShips.draw(g);
        } // end drawFrame()
     
        // empty methods below must be here for mouseEventListener   
        public void mousePressed(MouseEvent evt) { }
        public void mouseDragged(MouseEvent evt) { }    
        public void mouseReleased(MouseEvent evt) { }   
        public void mouseMoved(MouseEvent evt) { } 
        public void mouseEntered(MouseEvent evt) { }
        public void mouseExited(MouseEvent evt) { }
     
        public void mouseClicked(MouseEvent evt) 
        { 
               if (myFleetOfShips.getSide() == 5)
                        myFleetOfShips.setSide(10);
                 else
                        myFleetOfShips.setSide(5); 
               display.repaint();
        }
     
        public void actionPerformed(ActionEvent evt) // triggered by timer
        {
                //display.repaint();
        }
    }

    And try to run the "AnimateInTabFleetOfShips" class. It should compile fine and give no errors (at least in BlueJ) but the applet won't work.

    Sorry for making it so complicated but I really have no idea how to explain it simpler.

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    It's not that hard to explain, but it's hard to help you when you post code that isn't broken and expect us to break it to help you. Next time, just post the broken code to begin with and save 4 days.

    The reason your original code "works" is because the Square class has getSide() and setSide() methods used by the mouseClicked() method and Ship is an extension of Square, and FleetOfShips does not have those methods.

    I don't know BlueJ, but when you run the code, I'm guessing the Applet viewer tries to load the applet and stops at some point because of the error. The Applet viewer remains on screen and must be stopped abnormally, but the code you've written to fill it never completes, maybe never gets started.

    How to fix? Think about what should happen. You said earlier, when the mouse is clicked, every ship in a fleet should show the same change. Whether it's changing color or changing shape, all ships in the fleet should change. So the change shouldn't be applied to the fleet, it should be applied to EACH SHIP in the fleet. Something like:
    for ( Ship ship : myFleetOfShips )
    {
        // change the size to 5 if it is now 10 (code deleted)
        ship.setSide( 5 );
    }
    Hope this helps. If you still don't understand, ask. Post your updated code with questions.

  10. The Following User Says Thank You to GregBrannon For This Useful Post:

    macko939 (April 27th, 2014)

  11. #10
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My java homework (very simple stuff)

    I didn't post anything new in my last post, all the code was copied from the first one.

    Anyway, even if I put all the "on click" events in comments, the applet still doesn't draw these ships for me. I just get a blank black applet window without any ships on it.

    Sorry to be a pain.

  12. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    Not to be argumentative but to point out a difference in the code that's important because it's the source of your errors, this is the mouseClicked() method in the AnimateInTabSquare class from your first post:
        public void mouseClicked(MouseEvent evt) 
        { 
               if (mySquare.getSide() == 5)
                        mySquare.setSide(50);
                 else
                        mySquare.setSide(5); 
               display.repaint();
        }
    and this is the mouseClicked() method in the AnimateInTabSquare class from post number 8:
        public void mouseClicked(MouseEvent evt) 
        { 
               if (myFleetOfShips.getSide() == 5)
                        myFleetOfShips.setSide(10);
                 else
                        myFleetOfShips.setSide(5); 
               display.repaint();
        }
    Do you see the differences? Those differences are causing your problems due to the reasons I described in my last post.

  13. #12
    Junior Member
    Join Date
    Feb 2014
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: My java homework (very simple stuff)

    I must have missed that, sorry. Anyway, neither of these work and I either get a working applet but with black screen without any ships on it, or it crashes and I need to kill its process to be able to actually do something on my pc.

    I am really close to just give up on that and fail my java class, because I just can't figure this thing out at all and thats the last assignment I got. The most annoying thins is that I am unable to actually explain it clearly to people. I wasted my entire last week on this thing.

    All I need it to do is to draw these 5 ships for me in the applet viewer


    Our teacher gave us these PDL for a similar project, but with circles instead of squares and he told us to figure out how to do squares on our own.

    Ball
    http://pastebin.com/994sdBn5

    Dyad
    http://pastebin.com/Ev9VDir7

    FleetOfDyads
    http://pastebin.com/Lpk9pAsc

    I pretty much wrote all my code based on this, I have no clue whatsoever where I made a mistake.
    Last edited by macko939; April 27th, 2014 at 03:59 PM.

  14. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: My java homework (very simple stuff)

    I told you what to do in Post #9. Other than writing it for you, I'm not sure what else I can do.

Similar Threads

  1. Homework Help With Simple Java Programming
    By xxkronix in forum Java Theory & Questions
    Replies: 4
    Last Post: December 2nd, 2013, 06:29 PM
  2. about GUI stuff
    By nhiap6 in forum Java Theory & Questions
    Replies: 6
    Last Post: December 13th, 2012, 06:48 AM
  3. Simple Java Homework : Due Wendsday Afternoon PLZ HELP!
    By chatok90 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: November 30th, 2011, 05:58 PM
  4. help with homework - simple arrays
    By sensoryctascale in forum Java Theory & Questions
    Replies: 3
    Last Post: April 5th, 2011, 01:39 AM
  5. VB can do stuff Java can`t ??
    By JFujy in forum Java Theory & Questions
    Replies: 2
    Last Post: September 22nd, 2009, 10:25 AM