Using Swing Timer in Applet

I start a timer in the applet init method and restart/start the timer if it is not running in the applet start method. Since the start method is invoked by anther thread, it can run before the init method is completed. That is an undesired situation. What is the better way to handle the timer in this scenario?
Thanks.

Resolved!

Similar Messages

  • Can't dispose my dialog after moving it using swing timer.

    Hi all,
    I use the swing timer to move a dialog from one position to another. Here is the code I have use.
    // Set the main window display location
        public void setWindowLocation()
            int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
            int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            int frameHeight = this.getHeight();
            int frameWidth = this.getWidth();
            int _xValue = (screenWidth - frameWidth);
            int _yValue = (screenHeight - getTrayheight() );
            int _yEnd = (screenHeight - frameHeight - getTrayheight() );
            //this.setLocation((screenWidth - frameWidth), (screenHeight - frameHeight - getTrayheight() - WINDOW_SPACE));
            this.setLocation(_xValue, _yValue);
            while(_yValue > _yEnd){
                dialogMotion(this, _xValue, _yValue);
                _yValue -= 1;
            // this.dispose();
    // Dialog motion
        private void dialogMotion(final MainDialog mainDialog, final int x, final int y){
            AbstractAction abAction = new AbstractAction() {
                public void actionPerformed(ActionEvent evnt) {
                    mainDialog.setLocation(x, y);
            Timer motionTimer = new Timer(300, abAction);
            motionTimer.setRepeats(false);
            motionTimer.start();
    // Find the taskbar height to place the main frame in lower-right corner
    // of the viewable area of the screen.
        private static int getTrayheight(){
            return (Toolkit.getDefaultToolkit().getScreenSize().height -
                     GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height);
        }I think my code is clear to you. After moving the dialog onto the task bar, I want to dispose it. You can see that at the end of the while loop I've try it.
    What happened there is, I can't see the dialog moving. it directly dispose. I add a breakpoint at the while loop and check, it iterate until condition is false. But I can't see the motion. If I comment the dispose code line as in my above code, I can see it moving.
    Why is that. Your comment really helpful to me.
    I'm worried is that debugging iterate that while loop but it is not visible. :( :(

    Thanks a lot. I got the point all of you said. But it is bit confusing how to do it.
    As i said in my first post, used slightly similar code to move down the dialog. Here what I have try. But the question is because of my thread used there, it wait little amount to scroll down.
        private void hideWindow(MainDialog mainGialog){
            try{
                int _xAbove = mainGialog.getLocation().x;
                int _yAbove = mainGialog.getLocation().y;
                int _yBelow = mainGialog.getLocation().y + mainGialog.getHeight() + getTrayheight();
                while(_yBelow > _yAbove){
                    dialogScrollingUpDown(this, _xAbove, _yAbove);
                    _yAbove += 1;
                Thread.sleep(1000);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(1500);
                            dispose();
                        catch (InterruptedException e) {
                            e.printStackTrace();
            catch (Exception ex) {
                System.out.println(ex.getMessage());
        private void dialogScrollingUpDown(final MainDialog mainDialog, final int x, final int y){
            AbstractAction abAction = new AbstractAction() {
                public void actionPerformed(ActionEvent evnt) {
                    mainDialog.setLocation(x, y);
            Timer motionTimer = new Timer(400, abAction);
            motionTimer.setRepeats(false);
            motionTimer.start();
    // System tray height
        private static int getTrayheight(){
            return (Toolkit.getDefaultToolkit().getScreenSize().height -
                     GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height);
        }Actually I called the hideWindow method in a button clicked event. After clicked the button, it wait a time equal to the first thread sleep. I can't reduce the time, if so dialog dispose instant.
    Whay I can't do all those things is my IDE not allowed to use frequently changing values in dialogScrollingUpDown method. You can see that in my code.
    Any comments for that.

  • How to stop swing timer

    Hello,
    I use Swing timer in my application but it seems that timer.stop() does not work. I put System.out.println("hello") in the method that is the timer's actionlistener and even after I call timer.stop(), it keeps printing "hello". Is there any thing other than timer.stop() that I should do to stop the timer?
    Thanks a lot

    ladybean wrote:
    Thanks a lot for your reply. Well I only have one timer in the code. Another funny thing that is happening is that the timer gets faster over time. As you and I both know, this shouldn't be happening. I believe that you have one Timer variable, but are you sure that you don't have more than one Timer object? Again, this is just a SWAG, but this would also explain the increased speed over time.
    I set the delay time of 1 second but I see that my animation moves faster over time. The reason that I don't upload code is that it's really long and complicated. Maybe I should make it simpler and upload it. This is a very very good idea. We have a construct that's often used here called a SSCCE or "Short, Self Contained, Correct (Compilable), Example" that helps guide folks in creating a small compilable and runnable version of their problem, and often helps them to see their error for themselves (there's a lot to be said for simplifying the problem to examine it). Please have a look at this link for more details: [http://sscce.org/]
    Thanks again though. :)You're welcome. Oh, and if you do resolve this on your own, please post back to let us know what happened and why. Best of luck!

  • I can't use swing components in my applets

    When I write an applet without any swing components, my browser never has any trouble finding the classes it needs, whether they're classes I've written or classes that came with Java. However, when I try to use swing components it cannot find them, because it is looking in the wrong place:
    On my computer I have a directory called C:\Java, into which I installed my Java Development Kit (so Sun's classes are stored in the default location within that directory, wherever that is), and I store my classes in C:\Java\Files\[path depends on package]. My browser gives an error message along the lines of "Cannot find class JFrame at C:\Java\Files\javax\swing\JFrame.class"; it shouldn't be looking for this non-existent directory, it should find the swing components where it finds, for example, the Applet class and the Graphics class.
    Is there any way I can set the classpath on my browser? Are the swing components stored separately from other classes (I'm using the J2SE v1.3)?
    Thanks in advance.

    Without having complete information, it appears that you are running your applets using the browser's VM. Further, I assume you are using either IE or Netscape Navigator pre-v6. In that case, your browser only supports Java 1.1, and Swing was implemented in Java 1.2. You need to use the Java plug-in in order to use the Swing classes (see the Plug-in forum for more information), or else download the Swing classes from Sun and include them in your CLASSPATH.
    HTH,
    Carl Rapson

  • How can i connect multiple forms using swings or applets(AWT) & with D-Base

    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,

    sreedharkommuru wrote:
    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,There is no magic, you need to spend a good amount of time in tutorials, here is a good one to start off with:
    [The Really Big Index|http://java.sun.com/docs/books/tutorial/reallybigindex.html]
    Here are a few tips:
    1 - Do not mix AWT and SWING: it'll just cause you headaches in the long run that you cannot fix without refactoring to properly not mix the 2 together.
    2 - You use JDBC to access the database
    3 - You make accessors/constructors to pass parameters that you need from one form to another.
    Have fun.

  • Using Swing applet to write data to file on SERVER

    Hello,
    I'm in the process of writing an applet using Swing (SDK v1.4.2). Here's the deal. The JApplet calls a JPanel, which will be used by customers on my site to enter data. I'm adding a <Save> button to the "form" which is supposed to write data to a file on the server (in order to preserve the customer's preferences).
    Please note that I am NOT attempting to write data to the customer's hard disk. That requires digital certificates, etc. which I am trying to avoid for now.
    Instead, I am using the URL class to access the file:
    URL page = new URL("http://www.whatever.com/mycustomers/preferences.txt")
    I then use the URLConnection class to establish the connection:
    URLConnection conn = this.page.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.connect();
    etc...
    I've created a text file (preferences.txt) on my web site. Using the classes InputStreamReader, BufferedStreamReader, and StringBuffer, I can successfully read the file into a JOptionPane in my applet.
    The problem comes when I try to write data TO this file. I know the file exists because the applet can read it. I've set the permissions on the file to 666. I've got all of the appropriate syntax within a try statment that catches an IOException. I also have JOptionPanes all over the place to let me know where the program is. I've tried different combinations of output streams like BufferedWriter, BufferedOutputStream, StringWriter, but the file does not get updated. When the applet runs, it does not throw any exceptions, not even when I change the URL from "HTTP://www.whatever.com/prefs.txt" to "HTTP:/www.whatever.com/prefs.txt" (only one slash on HTTP, shouldn't I get a MalformedURLException?)
    I apologize for all the background, but I thought you might need it. The bottom line is:
    1) Can an applet write to a file on a remote server (not local hard disk)?
    2) If so, what (if any) caveats are there?
    3) Is there a way to check for file existence or be able to create a new file?
    4) I'm using the HTTP protocol - is there some restriction that prevents an applet from writing to a file using that protocol? If so, is there a workaround?
    5) Assuming that creating/writing a file using the method I've described is possible, what would be the appropriate output streams to use? (Currently, I'm using OutputStreamWriter with BufferedWriter).
    I've been struggling with this for a while. Any help/suggestions would be appreciated.
    Thanks
    P.S. I also posted this message on the Applet development forum, but I've received no response as of yet.

    Http servers support PUT as a mechanism to upload data to a specified URL. Get on the other hand which is what most people are familiar with is how you retrieve that data. The basic URLConnection is an abstraction of the Http connection which can be used for GET and POST operations by default based on doInput(true|false).. If you which to use any of the http methods other than GET|POST you will have to cast the URLConnection to HttpURLConnection so you can gain access to the specific Http functionaility that could not be abstracted.
    Since you are using a hosting service the chances are that you won't be able to use HTTP PUT on their server. Most servers do not support HTTP PUT without configuring them todo so. Now Apache allows localized config through the .htacess file. It might be possible (keep in mind I am not an apache expert) to configure a particular directory to allow HTTP PUT using this .htacess file it may not be possible. You will have to consult the Apache web server documentation for that answer.
    But regardless you can use the HttpURLConnection and the PUT method to send data from your applet to the server. In fact that is the preferred way to do this. If you can not configure your web server to support that method then you will have to develop a Servlet to do it. A servlet has several methods such as doGet(), doPost(), and doPut(). You would override the doPut() method get the URI path create a file and a FileOutputStream to that file, get from the request the inputstream, possibly skip the http headers, and then write byte for byte the incoming data to your OutputStream until you reach the end at which point you would close the OutputStream and send an Http Response of some sort. Typically in HTTP it would be 200 OK plus some web content. You content can be empty so long as your applet recognizes that is what it should expect...
    And away you go...

  • Using swing applet in IE

    Dear,
    Is there any way to use swing applet in IE.
    Thanks,

    If you are trying to make your code workable with Microsoft's VM, then I'd say you are looking for trouble. That VM's version is 1.1.4, if I'm not mistaken.
    Better stick to the JRE 1.4 with the plugin.

  • Progress bar on Applet using swing

    Not sure if this is Swing related or applet related, so I'll post it here... :-)
    Long work should be done on a Worker thread an not inside the Swing Dispacher thread .
    So normally I create a Runnable object that calls something like doWork(), and pass the runnable object as a parameter to the Sing utilities invokelater() function.
    My question is inside the worker thread how to update the GUI, in this case the progress bar?
    Can I just call from inside doWork() with no problems the progressbar.setValue(X)?
    Do I need to create another thread and use it too update the UI?
    Is something like this valid ?
    public void doWork() {
    // work work work
    progressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so on
    Thanks for the help!

    Not sure if this is Swing related or applet related,
    so I'll post it here... :-)It's definitely Swing related.
    Long work should be done on a Worker thread an not
    inside the Swing Dispacher thread . This is true.
    So normally I create a Runnable object that calls
    something like doWork(), and pass the runnable object
    as a parameter to the Sing utilities invokelater()
    function.This does not start a worker thread but rather schedules your Runnable object to be run on the EDT.
    My question is inside the worker thread how to update
    the GUI, in this case the progress bar?SwingUtilities or EventQueue have invokeLater and invokeAndWait specifically for this purpose.
    Can I just call from inside doWork() with no problems
    the progressbar.setValue(X)?
    Do I need to create another thread and use it too
    update the UI?No. Here's where you could use invokeLater.
    Is something like this valid ?
    public void doWork() {
    // work work work
    rogressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so onNo.
    >
    Thanks for the help!Like pete has pointed out, this seems to be a job for SwingWorker.

  • Desperately seeking help!! IE Crashes using Swing Applet

    Hi,
    I've created a grid applet using JTable and Swing in an applet. It runs great with data from a SQL database. I have at least 3 instances of the grid on the same page and other places on the site.
    However, Internet Explorer crashes frequently throwing an error "Unhandled exception at xxxxxxx in IExplore.exe (Beans.ocx).
    And the behavior is random and unpredictable.
    I've been desperately trying to look for help to fix this.
    Could someone please, please offer some suggestion?
    Thanks in advance,
    Anand.

    I agree. Try upgrading your plug-in version to 1.3.1. Keep in mind though that after 1.3.0, Sun changed where the plug-in looks for the root certificate. If you're using a Verisign or Thawte certificate, you shouldn't have any problems. If you're using your own certificate, you'll probably need to import it into the cacerts file in the lib/security directory under the installation directory of your jre.
    Hope this helps,
    Mark

  • Shall i use Swing or AWT for creating a chessboard applet??

    Hi,
    I need to build an applet which should dislpay a chessboard where i should
    be able to move the pieces around, read in a game analysis, etc...
    I am a beginner and i would like some advice on if i should use swing or awt?
    Which one is it easier to work with in terms of dispaying the pieces, moving the pieces and achieving other more challenging functionalities?
    Is it good idea to mix both of them? i.e have a japplet and use a canvas for displaying the board??
    Any advice would be much obliged.

    I used to think AWT
    And someone told me Swing was better..and that all of the Drag-n-Drop stuff doesn't work well with AWT.
    I have to admit that I used AWT up until a project about 3 months ago--I liked it better, but Swing does seem to have more builtins for handling the things you would need to for the Chess Board. Not that you CAN'T do them with AWT, but that they are harder to do with AWT.
    As far as reading in game analysis, etc..that really is independent of Swing/AWT

  • Don't know how to use the swing timer

    Hi there,
    I did this stupid game for training purposes: There are 3 buttons, 2 of them are "correct", 1 exits the program and you lost.
    It works so far but when clicking the "wrong" button I thought of changing the frame to red, let the program wait for another second and only then closing the window. But somehow that doesn't work. I understand that I have to use the timer class, but somehow I don't really know how.
    Thanks for helping.
    Modify the program of Exercise 3 so that only one button exits the program. If the user clicks on any of the other two
    buttons, the frame just changes color. The user keeps clicking until the "loosing button" is clicked. The user's goal
    is to click as many times as possible.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    public class Kap59A4 extends JFrame implements ActionListener
      JButton button1 ;
      JButton button2 ;
      JButton button3 ;
      JLabel noGames ;
      int gameCounter = 0;
      // constructor
      public Kap59A4(String title)                          
        super( title );
        button1 = new JButton("Button 1");
        button2 = new JButton("Button 2");
        button3 = new JButton("Button 3");
        noGames = new JLabel("Game#:  ");
        // register the Kap59A4 frame as the listener for the button.
        button1.addActionListener( this );
        button2.addActionListener( this );
        button3.addActionListener( this );
        setLayout( new FlowLayout() );
        add( button1 );
        add( button2 );
        add( button3 );
        add( noGames );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  
      public void actionPerformed( ActionEvent evt)
        Random rand = new Random();
        int number = Math.abs( rand.nextInt() )%3; // number gets a number from 0 to 2
        if (number != 0)
          gameCounter++;
          noGames.setText("Game#: "+ gameCounter);
          getContentPane().setBackground( Color.green );
          repaint();
        else
          getContentPane().setBackground( Color.red );
          new Timer(1000, this).start();
          System.exit(0);
      public static void main ( String[] args )
        Kap59A4 demo  = new Kap59A4( "Click a Button" ) ;
        demo.setSize( 300, 100 );    
        demo.setVisible( true );     
    }

    Rather than pass the Timer constructor this, which would be the JFrame itself, thus resulting in the action handler for the buttons being invoked again, you should probably pass it a whole different ActionListener instance that performs the precise action you want to happen a second later.
    And actually, you should probably do that for all the buttons as well -- give each an inner class implementing ActionListener so you can control the behavior of each button, and don't make the JFrame subclass implement ActionListener. Furthermore, I'd advise against subclassing JFrame.

  • System Time +Calendar using Swing

    Hi
    I'm trying to create Swing Appliation that displays the System time.but i don't know how to display it on the window.I imported package from java.util.calendar.* but i dont know how to use it.
    Also how can i create Calendar with help swing appliation?
    Sorry for my post in this thread but i' wasn't sure where to post it.So posted here.

    maheshkale wrote:
    I'm trying to create Swing Appliation that displays the System time.but i don't know how to display it on the window.I imported package from java.util.calendar.* but i dont know how to use it.--------
    I've written up a little clock widget that extends JLabel, so it should work with any Swing application. Hope it's not too long... Feel free to edit it. The enums are just for looks and can be replace with something else.
    It just works off of a Timer every second to update the time in the label, and can display in various formats.
    import javax.swing.JLabel;
    import java.awt.event.*;
    import java.util.*;
    * Simple clock display for JComponents. Displays in a variety of formats.
    public class Clock extends JLabel implements ActionListener {
         private static final long serialVersionUID = 1L;
          * Day of week.
         public static enum Day {
               * Sunday (0).
              SUNDAY( "Sunday", "Sun" ),
               * Monday (1).
              MONDAY( "Monday", "Mon" ),
               * Tuesday (2).
              TUESDAY( "Tuesday", "Tues" ),
               * Wednesday (3).
              WEDNESDAY( "Wednesday", "Wed" ),
               * Thursday (4).
              THURSDAY( "Thursday", "Thu" ),
               * Friday (5).
              FRIDAY( "Friday", "Fri" ),
               * Saturday (6).
              SATURDAY( "Saturday", "Sat" );
               * Full name of this day.
              public String name;
               * Shortened name of this day.
              public String s;
              Day( String name, String s ) {
                   this.name = name;
                   this.s = s;
          * A month of the year.
         public static enum Month {
               * January (0)
              JANUARY( "January", "Jan" ),
               * February (1).
              FEBRUARY( "February", "Feb" ),
               * March (2).
              MARCH( "March", "Mar" ),
               * April (3).
              APRIL( "April", "Apr" ),
               * May (4).
              MAY( "May", "May" ),
               * June (5).
              JUNE( "June", "Jun" ),
               * July (6).
              JULY( "July", "Jul" ),
               * August (7).
              AUGUST( "August", "Aug" ),
               * September (8).
              SEPTEMBER( "September", "Sep" ),
               * October (9).
              OCTOBER( "October", "Oct" ),
               * November (10).
              NOVEMBER( "November", "Nov" ),
               * December (11).
              DECEMBER( "December", "Dec" );
               * Full name of this month.
              public String name;
               * Shortened name of this month.
              public String s;
              Month( String name, String s ) {
                   this.name = name;
                   this.s = s;
          * This clock should display in words and numbers.
         public static final int ALPHANUMERIC = 1;
          * This clock should display in numbers.
         public static final int NUMERIC = 2;
          * This clock should only display the date.
         public static final int DATEONLY = 0;
          * This clock should display both date and time.
         public static final int DATETIME = 1;
          * This clock should display only the current hh:mm:ss time.
         public static final int TIMEONLY = 2;
          * Convenience value to mean the default choices (Date and Time in words and
          * numbers).
          * @see #ALPHANUMERIC
          * @see #DATETIME
         public static final int DEFAULT = 1;
         protected int display, what;
         protected javax.swing.Timer timer;
          * Create a new Clock with given display details and horizontal alignment.
          * <p>
    Display:<code><ul><li>ALPHA</li><li>ALPHANUMERIC</li><li>NUMERIC</li></ul></c
    ode>
          * </p>
          * <p>
    What:<code><ul><li>DATEONLY</li><li>DATETIME</li><li>TIMEONLY</li></ul></code
    >
          * </p>
          * The value <code>DEFAULT</code> applies for both.
          * <hr />
          * See <code>javax.swing.JLabel( String, int )</code>
          * @param display
          * @param what
          * @param align
         public Clock( int display, int what, int align ) {
              super( "", align );
              setDisplay( display );
              setWhat( what );
              timer = new javax.swing.Timer( 1000, this );
              timer.start();
         public void actionPerformed( ActionEvent evt ) {
              setText( getFormattedTime( display, what ) );
          * Get how this clock displays.
          * @return display
         public int getDisplay() {
              return display;
          * Get what this clock displays.
          * @return what
         public int getWhat() {
              return what;
          * Set how this clock displays.
          * @see #ALPHANUMERIC
          * @see #NUMERIC
          * @see #DEFAULT
          * @param display
          *        New <code>display</code> int.
         public void setDisplay( int display ) {
              this.display = display;
          * Set what this clock displays.
          * @see #DATEONLY
          * @see #DATETIME
          * @see #TIMEONLY
          * @see #DEFAULT
          * @param what
          *        New <code>what</code> int.
         public void setWhat( int what ) {
              this.what = what;
          * Get a formatted string of the current time according to given details.
          * @param display
          *        How to display.
          * @param what
          *        What to display.
          * @return Formatted <code>String</code>.
         public static String getFormattedTime( int display, int what ) {
              String ret = "";
              Calendar cal = Calendar.getInstance();
              switch ( what ) {
                   case DATEONLY:
                        int m = cal.get( Calendar.MONTH );
                        int d = cal.get( Calendar.DAY_OF_MONTH );
                        int w = cal.get( Calendar.DAY_OF_WEEK );
                        int y = cal.get( Calendar.YEAR );
                        switch ( display ) {
                             case ALPHANUMERIC: // dow, Mmm dd, yyyy
                                  Day wk = Day.values()[ w ];
                                  Month mn = Month.values()[ m ];
                                  ret += wk.name + ", " + mn.name + " ";
                                  ret += String.valueOf( d ) + getAfter( d );
                                  ret += ", " + String.valueOf( y );
                                  break;
                             case NUMERIC: // mm/dd/yyyy
                                  ret += String.valueOf( m ) + "/";
                                  ret += String.valueOf( d ) + "/";
                                  ret += String.valueOf( y );
                                  break;
                             default:
                        break;
                   case DATETIME:
                        ret += getFormattedTime( DATEONLY, what );
                        ret += " " + getFormattedTime( TIMEONLY, what );
                        break;
                   case TIMEONLY:
                        int hou = cal.get( Calendar.HOUR );
                        int min = cal.get( Calendar.MINUTE );
                        int sec = cal.get( Calendar.SECOND );
                        switch ( display ) {
                             case ALPHANUMERIC: // time is only numeric
                             case NUMERIC:
                                  ret += asString( hou ) + ":";
                                  ret += asString( min ) + ":";
                                  ret += asString( sec );
                        break;
                   default:
              return ret;
          * Format a number and return a string of length 2, with 0 preceeding any
          * value.
          * @param num
          *        Number to format.
          * @return "00", "0#", "##", etc...
         public static String asString( int num ) {
              String ret = String.valueOf( num );
              for ( int i = ret.length(); i <= 2; i++ ) {
                   ret += "0";
              return ret;
          * Return the "st", "rd", etc... after <code>day</code>.
          * @param day
          *        Day of month, 1-31
          * @return String
         public static String getAfter( int day ) {
              String ret = "";
              switch ( day ) {
                   case 1:
                        ret = "st";
                        break;
                   case 2:
                        ret = "nd";
                        break;
                   case 3:
                        ret = "rd";
                        break;
                   case 21:
                        ret = "st";
                        break;
                   case 22:
                        ret = "nd";
                        break;
                   case 23:
                        ret = "rd";
                        break;
                   case 31:
                        ret = "st";
                        break;
                   default:
                        ret = "th"; // everything else
              return ret;
    }Edited by: aaronabaci on Jan 6, 2008 9:49 PM

  • Help ! inaccurate time recorded using javax.swing.timer

    Hi All,
    I am currently trying to write a stopwatch for timing application events such as loggon, save, exit ... for this I have created a simple Swing GUI and I am using the javax.swing.timer and updating a the time on a Jlabel. The trouble that I am having is that the time is out by up to 20 seconds over a 10 mins. Is there any way to get a more accruate time ?? The code that I am using is attached below.
    private Timer run = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    timeTaken.setText("<html><font size = 5><b>" + (df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds++)) + "</b></font><html>");
    receordedTimeValue = ((df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds)));
    if (timeSeconds == 60) {
    timeMins++;
    timeSeconds = 0;
    if (timeMins == 60) {
    timeHours++;
    timeMins = 0;

    To get more accurate time you should use the System.currentTimeMillis() method.
    Try this code :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CountUpLabel extends JLabel{
         javax.swing.Timer timer;
         long startTime, count;
         public CountUpLabel() {
              super(" ", SwingConstants.CENTER);
              timer = new javax.swing.Timer(500, new ActionListener() { // less than or equal to 1000 (1000, 500, 250,200,100) 
                   public void actionPerformed(ActionEvent event) {
                        if (startTime == -1) {          
                             count = 0;               
                             startTime = System.currentTimeMillis();
                        else {
                             count = System.currentTimeMillis()-startTime;
                        setText(getStringTime(count));
         private static final String getStringTime(long millis) {
              int seconds = (int)(millis/1000);
              int minutes = (int)(seconds/60);
              int hours = (int)(minutes/60);
              minutes -= hours*60;
              seconds -= (hours*3600)+(minutes*60);
              return(((hours<10)?"0"+hours:""+hours)+":"+((minutes<10)?"0"+minutes:""+minutes)+":"+((seconds<10)?"0"+seconds:""+seconds));
         public void start() {
              startTime = -1;
              timer.setInitialDelay(0);
              timer.start();
         public long stop() {
              timer.stop();
              return(count);
         public static void main(String[] args) {
              JFrame frame = new JFrame("Countdown");
              CountUpLabel countUp = new CountUpLabel();
              frame.getContentPane().add(countUp, BorderLayout.CENTER);
              frame.setBounds(200,200,200,100);
              frame.setVisible(true);
              countUp.start();
    Denis

  • Should i use swing?

    hi
    fairly new to java GUIs and have been using AWT
    since
    a) my java book is a couple of years old and its coverage of swing isnt so good, and
    b) i dont really like the look of swing. it stands out from native programs too much. (i know i could use pl&f or whatever but i havent learnt that yet :) )
    but, since swing is new, should i use swing, or
    is it ok to still use AWT?
    thanks

    If you want trees, datecontroles, tabpanes, grids, shortcutkeyhandeling... Using swing would enable you to develop faster, because a lot of the components you would need are allready there, you dont have to make it all from scratch. About the look: If you make it all yourself you would have total control (It demands a great deal of skill and time though) There are other considerations as well. If you are developing applets swing is not a good idea (takes too long time to download) But often, speed of development is the most important consideration, and then swing often becomes the natural choice.
    Regards,
    Ragnvald Barth
    Software engineer.

  • Swing Timer issues on a faster machine.

    Hi everyone,
    I'm having some trouble using Swing Timers. I have built a system which uses three javax.swing.Timers, these are as follows:
    timerLeft = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt)
    {if(pathPointerLeft==leftCyclePoints.length) {
    pathPointerLeft=0;
    leftHandX=leftCyclePoints[pathPointerLeft][0];
    leftHandY=leftCyclePoints[pathPointerLeft][1];
    pathPointerLeft++;
    jugglingPanel.repaint();
    timerRight = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    if(pathPointerRight==rightCyclePoints.length) {
    pathPointerRight=0;
    rightHandX=rightCyclePoints[pathPointerRight][0];
    rightHandY=rightCyclePoints[pathPointerRight][1];
    pathPointerRight++;
    jugglingPanel.repaint();
    myApp.timerBalls = new Timer(myApp.timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt){
    for(int i=0;i<myApp.ballCycleVector.capacity();i++){
    myApp.ballPoints = (int[][])myApp.ballCycleVector.elementAt(i);
    if(myApp.startAnimatingBall){
    if(myApp.ballPoints[myApp.pathPointerBalls][2]==1 && myApp.transitionDone){
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(lastLocationX==myApp.ballPoints[myApp.pathPointerBalls][0] && lastLocationY==myApp.ballPoints[myApp.pathPointerBalls][1]) {
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=myApp.ballPoints.length) {
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    } else{
    myApp.pathPointerBalls=0;
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.pathPointerBalls++;
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls==myApp.ballPoints.length) {
    myApp.pathPointerBalls=0;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls][2]==0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.transitionDone=true;
    myApp.jugglingPanel.repaint();
    Apologies if these do not coform to standard coding conventions. When I run these on my home PC (P4 2.56GHz, 512MB RAM, 64MB Graphics) it runs beautifully. The same on a laptop (P3 1.8GHz, 512MB RAM, 64MB Graphics card). However, when I run it on the campus machines (3.20GHz, 1.5GB RAM, 128MB Graphics), the animated display (as controlled by the Timers above) stutters and does not remain in sync. I'm guessing that this is because it is being ran on a faster machine. Could anyone suggest a solution to this problem so that the animation remains in sync for a faster machine, or even suggest another reason why this problem is occuring. This is a very important project and I really need to resolve this issue. Thanks in advance.

    The code you posted means nothing:
    a) it is not readable, since you didn't use the "Code Formatting Tags" when you posted the code
    b) its not executable, so we can't see what it is attempting to do.
    c) we don't know the frequency of event firing
    Obviously a faster machine will be able to repaint Components faster then slower machines.
    I use a 3.3Ghz machine and my TimerAnimation example here seems to keep in sync:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

Maybe you are looking for