What is the flaw in this simple Swing program ?

Hi all ,
I tried one simple animation in Swing .
Here's what the program has to do :
when a button called "play" is clicked a circle should be moved from upper left corner down to the lower right corner.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyAnimation extends JFrame {
   int width;
   int height;
   MyAnimation animation ;
   MyDrawPanel drawpanel ;
   public static void main(String[] args) {
     MyAnimation gui=new MyAnimation();
     gui.go();
   } //close main()
   public void go() {
       animation = new MyAnimation();
       JButton button = new JButton("Play");
       button.addActionListener(new ButtonListener());
       drawpanel = new MyDrawPanel();
       animation.setTitle("Ball Animation");
       animation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       animation.getContentPane().add(BorderLayout.SOUTH,button);
       animation.getContentPane().add(BorderLayout.CENTER,drawpanel);
       animation.setSize(300,300);
       animation.setVisible(true);
   } //close go()
   class ButtonListener implements ActionListener {
       public void actionPerformed(ActionEvent ae) {
          for(width=0,height=0;width<130&&height<130;width++,height++) {
                   System.out.println("before calling");
                   animation.repaint();
                   System.out.println("W ="+width+"H ="+height);
               try {
                   Thread.sleep(50);
               }catch(Exception ex) { }
         } //close for
    } //close actionPerformed()
} //close ButtonListener
      class MyDrawPanel extends JPanel {
            public void paintComponent(Graphics g) {
               g.setColor(Color.blue);
               g.fillRect(0,0,this.getWidth(),this.getHeight());
               int w= this.getWidth();
               int h = this.getHeight();
               //System.out.print(w,h);
               g.setColor(Color.green);
               g.fillOval(width,height,40,40);
               System.out.println("paintcomponent");
           } //close paintcomponent()
     } //closeMyDrawPanel()
} //close MyAnimation()I noticed when a button is clicked everything goes fine(code reached Listener and loop is executed) expect that repaint() method is not invoked with in a loop(invoked only once at the end of loop).
but if I embed the same loop code with in go() method without a Listener class it's works Fine !
Why it's not happening when the code is within Litener class?
Two more additional questions :
What is the difference between calling the repaint() method with JFrame instance and JPanel instance ?
In that program why System.out.print() method which is in MyDrawPanel class can't be invoked ?
Thanks in advance

Axel_Richter wrote:
May be you could have a chance to animate without threads by using paintImmediately directly. I have never tried this, because to use threads is not so difficult at all.animation without explicit calls to thread:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyAnimation extends JPanel
    private static final int TIME_PERIOD = 10;
    private static final String PLAY = "Play";
    private static final String PAUSE = "Pause";
    private static final String RESET = "Reset";
    int width = 0;
    int height = 0;
    MyDrawPanel drawpanel = new MyDrawPanel();
    private Timer timer = new Timer(TIME_PERIOD, new TimerAL());
    public MyAnimation()
        super(new BorderLayout());
        setPreferredSize(new Dimension(300, 300));
        JButton button = new JButton("Play");
        button.addActionListener(new ButtonListener());
        add(button, BorderLayout.SOUTH);
        add(drawpanel, BorderLayout.CENTER);
    class ButtonListener implements ActionListener
        public void actionPerformed(ActionEvent event)
            String command = event.getActionCommand();
            if (command.equals(PLAY))
                timer.start();
                ((JButton)event.getSource()).setText(PAUSE);
            else if (command.equals(PAUSE))
                timer.stop();
                ((JButton)event.getSource()).setText(RESET);
            else if (command.equals(RESET))
                timer.stop();
                ((JButton)event.getSource()).setText(PLAY);
                width = 0;
                height = 0;
                repaint();
    class TimerAL implements ActionListener
        public void actionPerformed(ActionEvent arg0)
            if (width < (drawpanel.getWidth() - 40) &&
                    height < (drawpanel.getHeight() - 40))
                width++;
                height++;
                drawpanel.repaint();
            else
                timer.stop();
    class MyDrawPanel extends JPanel
        public void paintComponent(Graphics g)
            g.setColor(Color.blue);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            int w = this.getWidth();
            int h = this.getHeight();
            // System.out.print(w,h);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.green);
            g2.fillOval(width, height, 40, 40);
    private static void createAndShowGUI()
        JFrame frame = new JFrame("Ball Animation");
        frame.getContentPane().add(new MyAnimation());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable()
            public void run()
                createAndShowGUI();
}

Similar Messages

  • What's the problem of this mail sending program

    Hi,
    I have Written following code. I have wriiten & run this code in Eclipse. Mail.jar & Activation.jar both jar file i kept in the webcontent/web-inf/lib
    directory. & I also added this jar file using builpath->add External Library. But when run this code then it throws the following exception. What's the problem of code? IS there anybody can help me? Please help me.
    My code is : UserMail.jsp
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
    <title>Mail Sending Program</title>
    <%@ page import="javax.mail.internet.*"%>
    <%@ page import="javax.mail.*"%>
    <%@ page import="java.util.*"%>
    </head>
    <body>
    <%
    String to = "[email protected]";
    String from = "[email protected]";
    String host = "192.168.1.1";
    String txt = "I am from jsp of java";
    String subject = "For testing";
         Properties props = System.getProperties();
         props.put("mail.smtp.host", host);
         Session session1 = Session.getDefaultInstance(props, null);
         MimeMessage msg = new MimeMessage(session1);
         try{
              InternetAddress to1 = new InternetAddress(to);
        msg.setFrom(new InternetAddress(from));
       msg.addRecipient(Message.RecipientType.TO,to1);
       msg.setSubject(subject);
      msg.setText(txt);
          msg.setSentDate(new Date());
        Transport.send(msg);
         catch(Exception e){
              e.printStackTrace();
    %>
    </body>
    </html>Exception is:
    javax.mail.MessagingException: Could not connect to SMTP host: 192.168.1.1, port: 25;
      nested exception is:
         java.net.SocketException: Software caused connection abort: connect
         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
         at javax.mail.Service.connect(Service.java:275)
         at javax.mail.Service.connect(Service.java:156)
         at javax.mail.Service.connect(Service.java:105)
         at javax.mail.Transport.send0(Transport.java:168)
         at javax.mail.Transport.send(Transport.java:98)
         at org.apache.jsp.UserMail_jsp._jspService(UserMail_jsp.java:73)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.net.SocketException: Software caused connection abort: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
         at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
         ... 27 moreWith regards
    Bina

    javax.mail.MessagingException: Could not connect to SMTP host: 192.168.1.1Is this host Ip correct. If Ip is correct then this host should be a mail exchange server. Hope u did not use Ip address of ur machine ;-)
    By the way hope u recd the test mail during my testing....lol
    Regards
    Rohit

  • Can you figure out what was the problem in this simple 3 liner code?

    Hello, below is a class to demonstrate a problem I see that I can't understand. I create an instance of the enclosing
    class at class level, another instance in static main method. Class below fails at run time with stack overflow exception. It's all fine if one of those two instantiation steps is removed, What is wrong can anyone any ideas?
    public class App
    // create instance of this class     
    App app = new App();
    public static void main( String[] args )
         // create instance of this class again.
    App app2 = new App();
    System.out.println( "Hello World!" );
    }

    As soon as a new instance of 'App' is created, 'App app = new App();' is called, which calls 'App app = new App();' etc. Hence the stack overflow.
    When you remove 'App app = new App();', obviously, the stack overflow does not occur. And when your remove 'App app2 = new App();' the 'App' class is never instantiated and therefore, the exception is also not thrown.

  • What is the problem with this simple script

    This shouls work to open safari:
    tell application "Safari"
      activate
    end tell
    But I get error:
    error "Safari got an error: Connection is invalid." number -609
    So what is wrong? Other apps work such as:
    tell application "Adobe Bridge CS6"
      activate
    end tell

    Ah the Devils in the details.
    With the quit like that there is the potential for error.  When I add the quit I see either Safari not opening or else I get the connection error also.
    There are ways around this either put in a delay between the quit and the activate or else superficially check to see if Safari has quit.
    so
    tell application "Safari" to quit
    repeat while application "Safari" is running
    end repeat
    tell application "Safari"
      activate
    end tell
    or
    tell application "Safari" to quit
    delay 5 -- increase or decrease as needed
    tell application "Safari"
         activate
    end tell

  • What is the problem with this simple code?

    import javax.swing.*;
    public class TestThread extends JApplet implements Runnable
    JPanel jp;
    JLabel jb;
    public void init()
    jp=new JPanel();
    jb=new JLabel("Botton");
    getContentPane().add(jp);
    jp.add(jb);
    public static void main(String args[])
    new TestThread().start();
    public void run()
    System.out.println("Jaison");
    Y it not working...help me
    contd............
    <html>
    <head>
    </head>
    <applet
    code=TestThread.class
    width=1450
    height=1680>
    </applet>
    </html>

    Status bar says
    Applet TestThread StartedYou do know that main isn't used by applets? It will not be executed by the browser.
    Kaj

  • Please tell me what is the problem with this code

    Hai,
    Iam new to Swings. can any one tell what is the problem with this code. I cant see those controls on the frame. please give me the suggestions.
    I got the frame ,but the controls are not.
    this is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ex2 extends JFrame
    JButton b1;
    JLabel l1,l2;
    JPanel p1,p2;
    JTextField tf1;
    JPasswordField tf2;
    public ex2()
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setTitle("Another example");
    setSize(500,500);
    setVisible(true);
    b1=new JButton(" ok ");
    p1=new JPanel();
    p1.setLayout(new GridLayout(2,2));
    p2=new JPanel();
    p2.setLayout(new BorderLayout());
    l1=new JLabel("Name :");
    l2=new JLabel("Password:");
    tf1=new JTextField(15);
    tf2=new JPasswordField(15);
    Container con=getContentPane();
    con.add(p1);
    con.add(p2);
    public static void createAndShowGUI()
    ex2.setDefaultLookAndFeelDecorated(true);
    public static void main(String ar[])
    createAndShowGUI();
    new ex2();
    }

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ex2 extends JFrame
        JButton b1;
        JLabel l1,l2;
        JPanel p1,p2;
        JTextField tf1;
        JPasswordField tf2;
        public ex2()
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setTitle("Another example");
            b1=new JButton(" ok ");
            p1=new JPanel();
            p1.add(b1);
            p2=new JPanel();
            p2.setLayout(new GridLayout(2,2));
            l1=new JLabel("Name :");
            l2=new JLabel("Password:");
            tf1=new JTextField(15);
            tf2=new JPasswordField(15);
            p2.add(l1);
            p2.add(tf1);
            p2.add(l2);
            p2.add(tf2);
            Container con=getContentPane();
            con.add(p1, BorderLayout.NORTH);
            con.add(p2, BorderLayout.CENTER);
            pack();
            setVisible(true);
        public static void createAndShowGUI()
            ex2.setDefaultLookAndFeelDecorated(true);
        public static void main(String ar[])
            createAndShowGUI();
            new ex2();
    }

  • What is the point of this website?

    What is the point of this website? Questions asked but not answered. (I don't class the option to contact someone, at a certain time, in India, as a reasonable solution to what is a straightforward question). Has Adobe not got anyone qualified to answer my question? Is Elements 13 flawed? I've resorted to Elements 9 which works fine. If anyone asks me my opinion of Elements 13 I'll tell them "don't waste your money"!

    I would imagine it is this Photomerge problem:
    https://forums.adobe.com/thread/1654345?sr=stream <https://forums.adobe.com/thread/1654345?sr=stream&ru=3705263> &ru=3705263

  • What is the use of this form?

    Hi all,
    What is the use of this form in include RV61B901?
    How does this code send any information to the program calling it? Is Sy-subrc global so that main program will know the reuslts?
    Code:
    FORM KOBED_901.
      DATA : l_anzpk LIKE likp-anzpk.
      SELECT SINGLE anzpk FROM likp
                          INTO l_anzpk
                          WHERE vbeln = komkbv2-vbeln.
      IF l_anzpk NE 0.
        sy-subrc = 4.
        exit.
      ENDIF.
      sy-subrc = 0.
    ENDFORM.
    Thanks,
    Charles.

    Hello,
    This form sets the value of sy-subrc(which is global) based
    on the value of l_anzpk.
    Regards
    Greg Kern

  • MM - PO - what is the meaning of this button?

    Dear friends,
    Could anybody help me with one question.
    There is a strange button in a Purchasing Order on the Account Assignment tab page on this screenshot (it is marked with red color).
    Screenshot below
    http://content.foto.mail.ru/mail/raiden87/81/i-84.jpg
    What is the meaning of this button? When it is used for?
    I hope that anybody knows the meaning =)

    hi raiden,
    as for as i have gone through the issue I have come to know that:
    If you want to use multiple account assignment for a line item in PO then at that moment you will have to first press the "repeat on " button. only after that multiple account button will be active that is just before your "repeat on " button.
    Steps:
    1:Save your PO.
    2:Go to transaction code ME22N to change the PO.
    (Here you will firstly see that the multiple a/c assignment button is firsty gray.It will become active only after when you press the "repeat on" button).
    I hope It will be helpfull for you.
    regards,
    Aslam Ansari.

  • So I have an iPad with the smart cover, and it's usually supposed to turn on the iPad when u open it, but it's no doing that for me. Nor is it turning off without pressing the button. What is the meaning of this?

    So I have an iPad with the smart cover, and it's usually supposed to turn on and off the iPad when u open it and close it, but it's not turning on for me. Nor is it turning off without pressing the button. What is the meaning of this?what caused it to be this way? Is there someway that I could fix it?

    Wait a sec did this just start?
    You set up the smart cover function in settings (you did that, right?) so, if you did that and it's failed you make an appointment at your nearest Genius Bar now.

  • My Ipod touch is frozen.  Shows USB cable with arrow pointing to Itunes.  What is the problem?  This is the second one I have had that has done this!

    My Ipod touch is frozen.  The screen shows only USB cable with arrow point to the word Itunes.  What is the problem?  This is the second touch I have had that has this same problem.  HELP!

    This time try restoring the iPod to factory defaults/new iPod instead of from backup.  You may have some corruption that is causing the problem and it may now be in the backup.  If the problem persists after restoring to factory defaults/new iPod. then you likely have a hardware problem and ana ppointment at the Genius Bar of an Apple store is in order.

  • What is the wrong in this PL/SQL  block

    Hi a...
    Can you please tell what is the wrong in this pl/sql block.
    declare
    TYPE TYP_NT_NUM IS TABLE OF NUMBER ;
    v_tab TYP_NT_NUM := TYP_NT_NUM();
    TYPE uname is VARRAY(30) of varchar2(100) ;
    usr uname := uname ( 'u1','u2','u3','u4' );
    TYPE pwd is VARRAY(30) of varchar2(100) ;
    psw pwd := pwd('p1','p2','p3','p4');
    x number(10):=0;
    Cursor fcid IS Select distinct FC_ID From FCMASTER ;
    Begin
    Open fcid ;
    --for ii in usr.first .. usr.last loop
         Loop
              Fetch fcid Into x ;
              Exit When fcid%NOTFOUND ;
              v_tab(fcid%ROWCOUNT) := x ;
         End loop ;
         For iii IN v_tab.FIRST .. v_tab.LAST Loop
              dbms_output.put_line(v_tab(iii).FC_ID) ;
              End loop ;
    End loop; End of outer loop
    End;
    The error is
    Error
    [row:28,col:36] ORA-06550: line 28, column 36:
    PLS-00487: Invalid reference to variable 'NUMBER'
    ORA-06550: line 28, column 4:
    PL/SQL: Statement ignored
    Thanks in advance,
    Pal

    v_tab(iii).FC_ID
    declare
      type typ_nt_num is table of number;
      v_tab typ_nt_num;
    begin
      select distinct object_id bulk collect into v_tab from all_objects where rownum <= 10;
      for i in 1 .. v_tab.count loop
        dbms_output.put_line(v_tab(i)) ;
      end loop ;
    end;
    /

  • I am trying to listen BBC radio news from BBC App, but on pressing the button I always get the error "there was an error playing this radio feed". What is the source of this error and how can I remove it?

    I am trying to listen BBC radio news from BBC App, but on pressing the button "live radio" I always get the error "there was an error playing this radio feed". What is the source of this error and how can I remove it?

    That is probably just a generic error message and you might not ever know what is causing it. Assuming that you have been able to play live radio with the app in the past (I know nothing about the app) and assuming that all other Internet related functions (Safari, email, etc.) are working properly on your iPad, quit the app completely and reboot your iPad.
    Go to the home screen first by tapping the home button. Double tap the home button and the recents tray will appear with all of your recent apps displayed at the bottom. Tap and hold down on any app icon until it begins to wiggle. Tap the minus sign in the upper left corner of the app that you want to close. Tap the home button or anywhere above the task bar.
    Reboot the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider if it appears on the screen - let go of the buttons. Let the iPad start up.
    If that fails to resolve the issue, you might want to reboot your router, unplug it for about 30 seconds and then plug it in again.

  • TS1702 I use iphone5, I see an app update on the app store. but when App store and click on the update tab, it doesn't show me which application to update.. just give me a blank page.!!!! what is the solution for this.!!!!

    I use iphone5, I see an app update on the app store. but when App store and click on the update tab, it doesn't show me which application to update.. just gives me a blank page.!!!! I wouldn't able to know what app has to be updated, untill and unless i get check for each every app on the app store installed on my iphone... what is the solution for this.!!!! can any1 one help me out.!!!!

    Cc2528 wrote:
    The iTunes Store on my iPad is set up with all my music already. And at the very bottom it shows my apple Id username. The only place it shows the previous owners id is in the App Store...
    You can probably change the ID in the "iTunes and App stores" settings on the iPad....click on the wrong account ID , select sign out, then log in with your own ID, I have not done this but I think it works.....
    but I would be more inclined to to the factory reset and start afresh.

  • What is the uses of this programe(accelerometer)?

    what is the uses of this programe(accelerometer) in N95 original or N95 8g and from where I can get it?

    This is Rotateme, but needs to be signed.
    http://www.bysamir.fr/rotateme/
    This is the movingball which just needs to be installed (doesn't require signing).
    http://research.nokia.com/files/MovingBall_Example.sisx
    Nokia N95
    V 20.0.015
    0546553

Maybe you are looking for

  • Report on deleted workstations

    Is it possible to run a report on deleted workstations in ZCM 10.2. This could be done in ZAM7.5 and was a standard report. Should we be retiring devices now as opposed to deleting obsolete inventory? ie run a report where device=deleted I don't seem

  • Itunes 8 in Windows Vista

    Error itunes is running in compatibily mode. The icon on the computer went bigger. And I known is not. That happens when upgrade. The icon on the computer went bigger. Please help.

  • How do you change the font size on text message

    The font on my texting message is really big and how do I change it?

  • Error with ant build and JUnit task in IntelliJ

    Hi, I seem to be having a very annoying error in IntelliJ. Here are the stats: - IntelliJ 4.5.1, Build 2239 - Using own version of ant (1.5.1) - removed junit37.jar from my ant1.5.1/lib dir, and instead added junit version 3.8.1 of junit.jar to that

  • Dum using select statement on STXL :SV_TNEW_PAGE_ALLOC_FAILED

    Hi all, Below select query is throwing a dump SV_TNEW_PAGE_ALLOC_FAILED  . The total records which are there in database for the below selection is around 5 Lac record.The dump occured because at the point The internal table "IT_33" could not be enla