#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0

    Help animating/moving a JPanel


    Hi, i'm new to Java and i have started a personal project for college. The module is based around Swing and i understand the principles of using swing as a GUI and have made the framework of my project for the criteria below. I now need to write code to make to JPanels move randomly around the screen and make the JButtons perform their required actions. Any help or advice would be much appreciated. (I've attached the frog.bmp if that helps anyone)

    Criteria:
    You will develop a Swing-based GUI on which is depicted a frog and a fly.

    The frog is depicted by a drawing from a .gif or .jpg or .bmp file. The fly is represented by a graphics component of a small square dot . The pet is not actually animated, but both pet and prey images can move in 2 dimensions on a JPanel within the GUI.

    The GUI should provide the following capabilities

    1. A ‘Make Pet’ button.
    2. The pet must have a name and it must not be possible for the pet to appear on the screen until it has been given a name. You will need a means of entering the pet’s name on the GUI.
    3. The pet and its prey should now appear on the screen in random starting positions, and start to move in random steps without it being possible for either to move off the screen.
    4. The GUI should possess a “Hungry” button which when pressed causes the pet to move towards its prey in steps of fixed length, while the prey continues to move in a random fashion.
    5. At the bottom of the GUI there should be another JPanel with a JTextArea. When “Hungry” is pressed, the text area should display “<name> is hungry”.
    6. When the fly is within a pre-determined distance from the frog, the frog ‘eats’ the fly shooting out a long red tongue that touches the fly and then the tongue and fly disappears and the fly is assumed to be eaten.
    7. The text area should now display “<name> is no longer hungry” and the frog should revert back to moving in a random fashion.
    8. There should be no limit on the number of frogs (each with its own fly) that can be placed on the screen. Each frog and fly must be able to move independently and continuously. When the “Hungry” button is pressed all frogs become hungry and all go after their own fly (not necessarily the closest fly).
    9. Finally there should be a “Reset” button where the screen and text area is cleared.

    My code so far:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    
    public class Cyberpet extends Component{
              
    	JPanel namePanel, imagePanel, flyPanel;
    	JLabel namePetLabel, hungryLabel;
    	JTextField petNameField;
    	JButton enterButton, makeButton, hungryButton, resetButton ;
        
    	BufferedImage img;
    
        public void paint(Graphics g) {
            g.drawImage(img, 0, 0, null);
        }
    
        public Cyberpet() {
           try {
               img = ImageIO.read(new File("frog.bmp"));
           } catch (IOException e) {
           }
    
        }
        
        public Dimension getPreferredSize() {
            if (img == null) {
                 return new Dimension(0, 0);
            } else {
               return new Dimension(img.getWidth(null), img.getHeight(null));
           }
        }
            
        public JPanel createContentPane (){
            
            JPanel totalGUI = new JPanel();
            totalGUI.setBackground(Color.CYAN);
            totalGUI.setLayout(null);
            
            imagePanel = new JPanel();
            imagePanel.add(new Cyberpet());
            imagePanel.setLocation(0, 0);
            imagePanel.setSize(152, 152);
            imagePanel.setVisible(true);
            totalGUI.add(imagePanel);
            
            JPanel flyPanel = new JPanel();
            flyPanel.setBackground(Color.black);
            flyPanel.setLocation(200, 200);
            flyPanel.setSize(10, 10);
            totalGUI.add(flyPanel);
                    
            namePanel = new JPanel();
            namePanel.setLayout(null);
            namePanel.setLocation(290, 190);
            namePanel.setSize(200, 150);
            namePanel.setBackground(Color.white);
            namePanel.setVisible(true);
            totalGUI.add(namePanel);
            
            namePetLabel = new JLabel("Name Your Pet");
            namePetLabel.setLocation(50, 0);
            namePetLabel.setSize(200, 30);
            namePanel.add(namePetLabel);
            
            petNameField = new JTextField(8);
            petNameField.setLocation(50, 40);
            petNameField.setSize(100, 30);
            namePanel.add(petNameField);
            
            enterButton = new JButton("Enter");
            enterButton.setLocation(50, 100);
            enterButton.setSize(100, 30);
            namePanel.add(enterButton);
            
            makeButton = new JButton("Make A Pet");
            makeButton.setLocation(50, 500);
            makeButton.setSize(100, 30);
            totalGUI.add(makeButton);
            
            hungryButton = new JButton("Hungry");
            hungryButton.setLocation(650, 500);
            hungryButton.setSize(100, 30);
            totalGUI.add(hungryButton);
            
            resetButton = new JButton("Reset");
            resetButton.setLocation(650, 50);
            resetButton.setSize(100, 30);
            totalGUI.add(resetButton);
            
            hungryLabel = new JLabel("Your Frog is hungry");
            hungryLabel.setLocation(330, 500);
            hungryLabel.setSize(200, 30);
            totalGUI.add(hungryLabel);        
         
            totalGUI.setOpaque(true);
            return totalGUI;
            
         }
    	
    private static void createAndShowGUI() {
    	
        JFrame frame = new JFrame("Cyberpet");
        
        Cyberpet demo = new Cyberpet();    
    
        frame.setContentPane(demo.createContentPane());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
    
    public static void main(String[] args) {
    	
    
    	SwingUtilities.invokeLater(new Runnable() {
            public void run() {
           	 createAndShowGUI();
           	 
                
            }
        });
    }}
    The frog
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    What problems are you having now? Can you ask some specific questions about the next feature you are trying to add to the code?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by NormR
    What problems are you having now? Can you ask some specific questions about the next feature you are trying to add to the code?
    I need to add some actions to the buttons such as generating a frog and resetting the whole frame but the part i am really struggling with is getting the JPanels to move around the content pane in random directions. I've tried Googleing it and i've found examples of shapes bouncing around but nothing about moving a JPanel. Is it possible for a JPanel to move in random directions and how would i go about it please?
  6. #4
  7. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    getting the JPanels to move around the content pane
    What have you tried?
    An idea for testing a technique:
    Remove the layout manager for the container by setting it to null.
    Add a JPanel to the container and use its setBounds() method to position it somewhere in the container.
    When that works, add some code to a button listener that will change the JPanel's location.
    When that works you'll see what it takes to move a JPanel in a container and then can work on the fancy stuff you want the program to do.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    I haven't tried anything sorry i didn't know where to start. I'll try what you said thanks.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by NormR
    What have you tried?
    An idea for testing a technique:
    Remove the layout manager for the container by setting it to null.
    Add a JPanel to the container and use its setBounds() method to position it somewhere in the container.
    When that works, add some code to a button listener that will change the JPanel's location.
    When that works you'll see what it takes to move a JPanel in a container and then can work on the fancy stuff you want the program to do.
    I've written a method that i think would make the JPanel move randomly around the contentPane and bounce off the edges but i have no idea how to apply it to the setBounds of the JPanel:

    Code:
    void move() {
           positionx = (int)Math.random() * 750;
           positiony = (int)Math.random() * 550;
           dx=20;
           dx=20;
           positionx += dx;
           positiony += dy;
           if (positionx > 800 || positionx < 0)
        	   dx=-dx;
           if (positiony > 600 || positiony < 0)
        	   dy=-dy;
        }
    I've also since written ActionListeners for the buttons for naming the pet ect so getting the JPanels to move around is the next thing i have left to work out. Any help would be really appreciated thanks!
  12. #7
  13. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    how to apply it to the setBounds of the JPanel:
    Look at the methods for the Component class that will set its location.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by bevitngton2
    I've attached the frog.bmp if that helps anyone
    Sorry i forgot the internet doesn't like bitmaps, you can use your imagination

    Originally Posted by NormR
    Look at the methods for the Component class that will set its location.
    Please could you explain further, i don't really understand the Component class i just knew i had to extend my class from it to get the image to import from previous examples i had done.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    The component class has the method
    "void setLocation(int x, int y)
    Moves this component to a new location."

    But i don't know how to make this only apply to the JPanel imagePanel that contains my image of a frog.
  18. #10
  19. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    Look in the API doc for the Component class. All its methods are described there:
    http://docs.oracle.com/javase/7/docs/api/

    Find the class name in the lower left and click on the link to have the API doc displayed in the main frame.

    how to make this only apply to the JPanel imagePane
    Call the method for the object you want to set the location of and pass it the x and y locations where you want the object to be.
    Last edited by NormR; February 26th, 2013 at 06:05 AM.

IMN logo majestic logo threadwatch logo seochat tools logo