Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By jim829

Thread: Calling a method from main

  1. #1
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Calling a method from main

    First, I'd like to thank Jim for helping me create the foundation of my code. I'm on a different project now that is built to resolve a flicker problem with a very simple animation. I'm am extremely new to Java so this will probably be very easy question for someone to answer. I need to know how to call the following method from main:
    Java Code:
       public static void main(String[] args) 
        {
            SmoothAnimation sa = new SmoothAnimation();
            sa.size_and_show();
            sa.startThread();
            sa.repaint();
        }
    Here's the method:
    Java Code:
        public void update(Graphics g)
        {
            if(x++ > width)
            {
                x = -height;
            }
            if (image == null)
            {
                image = createImage(width, height);
            }
            Graphics ig = image.getGraphics();
            paint(ig);
            g.drawImage(image, 0, 0, this);
            System.out.println("Initialized");
        }
    I've tried bypassing this method by adding the code to my paint method and that fails. I've tried using
    Java Code:
    sa.update(null)
    in the main method and that fails as well. Here is the whole program if anyone has any ideas to help. Basically I'm trying to create an image in memory so that the rectangle and moving circle do not have to constantly refresh which is causing the flicker. Thanks for the help...Jason
    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Dimension;
    
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    
    public class SmoothAnimation extends JPanel implements Runnable
    {
        private JFrame frame;
        private int width = 400;
        private int height = 100;
        private int x = -height;
        private int y = 0;
        private Thread looper;
        private Image image;
        
        public static void main(String[] args) 
        {
            SmoothAnimation sa = new SmoothAnimation();
            sa.size_and_show();
            sa.startThread();
            sa.repaint();
        }
        
        public SmoothAnimation()
        {
            frame = new JFrame("Smooth Animation");
            frame.add(this);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLayout(null);
        }
        
        public void size_and_show()
        {
            setPreferredSize(new Dimension(width, height));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
        
        public void startThread()
        {
            looper = new Thread(this);
            looper.start();
        }
        
        public void run()
        {
            try
            {
                while(true)
                {
                    Thread.sleep(33);
                    /*if(x++ > width)
                    {
                        x = -height;
                    }*/
    
                    repaint();
                }
            }catch(Exception e)
            {
                System.out.println(e.getStackTrace());
                System.exit(1);
            }
        }
        
        public void update(Graphics g)
        {
            if(x++ > width)
            {
                x = -height;
            }
            if (image == null)
            {
                image = createImage(width, height);
            }
            Graphics ig = image.getGraphics();
            paint(ig);
            g.drawImage(image, 0, 0, this);
            System.out.println("Initialized");
        }
        
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.setColor(Color.black);
            g.fillRect(0, 0, width, height);
            g.setColor(Color.blue);
            g.fillOval(x, y, height, height);
        }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Calling a method from main

    Overriding suggestion that has nothing to do with your actual question but all to do with your problem: don't override the update(Graphics g) method of a Swing GUI. This is done for AWT GUI's but not for Swing.

    Having said that you shouldn't be messing with Graphics contexts in the way you're trying anyway. What are you trying to achieve with the update(...) method anyway?
    Last edited by Fubarable; 06-29-2013 at 10:44 PM.

  3. #3
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    I'm trying to create a memory image. My video instructor uses much outdated code and I have had multiple issues getting his AWT GUI's to work, especially with loading images. I'm trying to rewrite the code he supplies so that it works and Swing GUI's seem to make otherwise unusable code work for me. I can get the simple animation to run; however, I can't get the memory image to take. I'm trying to use as much of the instructor's code as I can and reform it to a Swing GUI so I can follow along with his lessons. How would I go about creating a memory image in memory for a Swing GUI? Thanks, Jason
    Last edited by speedbump164; 06-30-2013 at 12:20 AM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Calling a method from main

    It sounds like what you're trying to do is to double-buffer your graphics. Swing does this automatically for you if you draw in a paintComponent method of a JComponent-derived object, which it appears that you're doing.

    Other optimizations:
    • Create an image of your red ball and draw it, translated appropriately.
    • Only repaint the select region of interest.


    For example:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class SmoothAnimation2 extends JPanel {
       private static final int PREF_W = 400;
       private static final int PREF_H = 100;
       private static final Color BACKGROUND = Color.black;
       private static final Color BALL_COLOR = Color.red;
       private static final int TIMER_DELAY = 33;
       public static final int DELTA_X = 1;
       public static final int IMAGE_DELTA_X = 5 * DELTA_X;
       private BufferedImage ballImage;
       private int ballImgX = -PREF_H;
    
       public SmoothAnimation2() {
          setBackground(BACKGROUND);
          ballImage = createBallImage();
          new Timer(TIMER_DELAY, new TimerListener()).start();
       }
       
       private BufferedImage createBallImage() {
          BufferedImage ballImg = new BufferedImage(PREF_H, PREF_W, BufferedImage.TYPE_INT_ARGB);
          Graphics2D g2 = ballImg.createGraphics();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(BALL_COLOR);
          g2.fillOval(0, 0, PREF_H, PREF_H);
          g2.dispose();
          return ballImg;
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          if (ballImage != null) {
             g.drawImage(ballImage, ballImgX , 0, this);
          }
       }
       
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
       
       private class TimerListener implements ActionListener {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
             ballImgX += DELTA_X;
             ballImgX = ballImgX >= PREF_W ? -PREF_H : ballImgX;
             
             int x = Math.max(0, ballImgX - IMAGE_DELTA_X);
             int y = 0;
             int width = PREF_H + IMAGE_DELTA_X;
             int height = PREF_H;
             
             repaint(x, y, width, height);
             
             // to get the drabs left over on the right side side
             if (x == 0) {
                x = PREF_W - IMAGE_DELTA_X;
                repaint(x, y, width, height);
             }
          };
       }
    
       private static void createAndShowGui() {
          SmoothAnimation2 mainPanel = new SmoothAnimation2();
    
          JFrame frame = new JFrame("SmoothAnimation2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Last edited by Fubarable; 06-30-2013 at 12:43 AM.

  5. #5
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    Wow. Thanks. I'll have to look over this code and see if I can understand what's happening. I'm very new to Java.

  6. #6
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    Can you still tell me how I'd go about calling my update(Graphics g) method from main so I know for future reference. Thanks, Jason

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Calling a method from main

    You do *not* invoke any method of a visual Component that requires a Graphics parameter. Not update(...), not paint(...), not paintComponent(...). After changing the state in a way that affects a component's visible representation, call repaint(). That queues a painting event which results in the painting method being called with an appropriate Graphics reference, appropriately clipped and translated to paint within the bounds of the component.

    And as already mentioned in this thread. any program that has an override of update(...) is legacy code that might have been in vogue more than a decade ago.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    Quote Originally Posted by DarrylBurke View Post
    And as already mentioned in this thread. any program that has an override of update(...) is legacy code that might have been in vogue more than a decade ago.
    db
    I'm sorry that I seem to be asking the same question over & over but I have no idea what override of update(...) means or the part about legacy code being in vogue. I'm assuming it means outdated code. Why does paint run all by itself but update(Graphics g) doesn't? Why won't adding the code into the paint method work? I've created a memory image with a Swing GUI before using the paint method and it worked just fine. I can also get this animation to work just fine with the Swing GUI by bypassing the update method completely and not creating the memory image. Honestly, I don't even see a flicker that needs to be fixed. It runs smoothly. I'm just trying to follow along with the archived course. The code that was given to help me above has me completely stumped because I am so new to Java. Thanks for the help, Jason

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,923
    Rep Power
    5

    Default Re: Calling a method from main

    I recommend reading the following: Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing). Make certain you click on the include link Painting in AWT and Swing. It discusses both the AWT painting model and the Swing model. Unfortunately, the links to examples in the second URL don't resolve properly (probably as an artifact of when Oracle bought out Sun). The bottom line is that Swing makes painting much easier. Personally, I would avoid any tutorial which discusses Frame, Panel, Canvas, or overriding update() and paint() as those date back to AWT before Swing. Thus far, all I use are repaint() and, when appropriate, repaint() with a specified clip region.

    Regards,
    Jim
    Fubarable likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    Thanks Jim. I'll check that out. Unfortunately, the lessons I'm paying for all use frame & canvas. I need to find a legitimate online course that I can pay for to learn modern Java.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,923
    Rep Power
    5

    Default Re: Calling a method from main

    Well, my preferred method of learning any language is reading a book (a "real" book, not online). Once you get one language under your belt, the rest are easier to learn. But you should be able to find some reputable online tutorials for free that teach current Java programming techniques. If it is pre-Java 1.5 then look elsewhere.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    speedbump164 is offline Member
    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Default Re: Calling a method from main

    I bought the Java for Dummies book and a couple of others but I think it is 2005 Java code so I'm stuck in the same boat. I guess I can keep looking but it's difficult to tell which version of Java they are talking about. Thanks for the help Jim...Jason

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,277
    Rep Power
    6

    Default Re: Calling a method from main

    Quote Originally Posted by speedbump164 View Post
    I bought the Java for Dummies book
    You poor, poor man. I feel so sorry for your loss :(

Similar Threads

  1. Calling args from main method
    By bogojevicka in forum New To Java
    Replies: 3
    Last Post: 01-16-2012, 10:34 PM
  2. Calling args from main method
    By bogojevicka in forum Suggestions & Feedback
    Replies: 2
    Last Post: 01-16-2012, 09:33 PM
  3. Calling into the main method
    By vcardell in forum New To Java
    Replies: 4
    Last Post: 11-02-2011, 01:16 AM
  4. Calling main method
    By eva in forum New To Java
    Replies: 7
    Last Post: 11-06-2009, 02:37 PM
  5. calling method from main method
    By bob_bee in forum New To Java
    Replies: 4
    Last Post: 10-02-2009, 06:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •