Class Timer

I don't know why this code doesn't work:
Timer t = new Timer(500, new TimerAction());
t.start();
The error is: Invalid method declaration.
TimerAction is class which implements ActionListener
Please help me!

This is my code it works but server doesn't received message "FromTimer"
It Receves only "Send" messages. Why?
package chat;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;
public class MyChatRoom extends JFrame implements ActionListener{
//TimerAction myTimer = new TimerAction();
Timer t = new Timer(500, new TimerAction());
t.start();
class TimerAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
socket = new Socket("localhost", 1001);
toServer = new PrintStream(socket.getOutputStream());
frmServer = new ObjectInputStream(socket.getInputStream());
toServer.println("FromTimer");
Vector vector = (Vector) frmServer.readObject();
int i = messageCount;
for(;i < vector.size();i ++) {
areaSentMessages.append((String) vector.elementAt(i));
areaSentMessages.append("\n");
messageCount = i;
} catch(Exception e1) {
System.out.println("Exception occured" + e1);
Vector vector;
JLabel lblNewMessage;
JLabel lblSentMessages;
JLabel lblUsers;
JTextArea areaSentMessages;
JTextArea areaUsers;
JTextField txtNewMessage;
JButton btnSend;
JButton btnLogOut;
JScrollPane jspSentMessages;
JScrollPane jspUsers;
JPanel pnl;
String userName;
String removeName;
Socket socket;
PrintStream toServer;
ObjectInputStream frmServer;
//String message;
int messageCount = 0;
public MyChatRoom(String name) {
Timer t = new Timer(500, new TimerAction());
vector = new Vector();
userName = new String(name);
removeName = new String(name);
setTitle("Chat Room :" + userName);
pnl = new JPanel();
pnl = (JPanel)this.getContentPane();
pnl.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
lblSentMessages = new JLabel("Sent Messages");
pnl.add(lblSentMessages, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
lblUsers = new JLabel("Users");
pnl.add(lblUsers, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.weighty = 1;
areaSentMessages = new JTextArea(20, 30);
jspSentMessages = new JScrollPane(areaSentMessages,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.
HORIZONTAL_SCROLLBAR_AS_NEEDED);
pnl.add(jspSentMessages, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.weighty = 1;
areaUsers = new JTextArea(20, 10);
jspUsers = new JScrollPane(areaUsers,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pnl.add(jspUsers, gbc);
JPanel pnlMessage = new JPanel();
lblNewMessage = new JLabel("Message ");
pnlMessage.add(lblNewMessage);
txtNewMessage = new JTextField(25);
pnlMessage.add(txtNewMessage);
gbc.gridx = 0;
gbc.gridy = 2;
pnl.add(pnlMessage, gbc);
JPanel pnlButtons = new JPanel();
btnSend = new JButton(" Send ");
pnlButtons.add(btnSend);
btnSend.addActionListener(this);
btnLogOut = new JButton("Log Out");
pnlButtons.add(btnLogOut);
btnLogOut.addActionListener(this);
gbc.gridx = 1;
gbc.gridy = 2;
pnl.add(pnlButtons, gbc);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(550, 450);
show();
public void actionPerformed(ActionEvent event) {
JButton button = new JButton();
button = (JButton) event.getSource();
if(btnSend.equals(button)) {
try {
socket = new Socket("localhost", 1001);
frmServer = new ObjectInputStream(socket.getInputStream());
toServer = new PrintStream(socket.getOutputStream());
String message = txtNewMessage.getText();
toServer.println("Send");
toServer.println(userName + ":" + message);
txtNewMessage.setText("");
vector = (Vector) frmServer.readObject();
int i = messageCount;
for(;i < vector.size();i ++) {
//System.out.println(vector.elementAt(messageCount));
areaSentMessages.append( (String) vector.elementAt(i));
areaSentMessages.append("\n");
messageCount = i;
} catch(Exception e) {
System.out.println("Exception occured " + e);
public static void main(String[] args) {
String name = new String();
new MyChatRoom(name);
}

Similar Messages

  • Using Class Timer  in a client/server app

    In my program i d like the server execute draws every 5 min choosing numbers randomly from1 to 10.
    Clients, when connected will inform server about the number they chose. (This works correctly)
    Next, the clients will wait until notified by the server about the number drawn in the last draw and
    about if they won or not.
    i ve found that i have to use classes Timer and TimerTask but API does not help me enough
    about how to use them. Could anyone help me?
    Here is the piece of code i think it need to be changed.
      // control thread's execution
          public void run()
             int message=0;
             int rnum=randGen.nextInt(10);
             display.append( "\n"+ "THE MAGIC NUMBER IS: " + rnum );
    // process connection
             try {
                // read message from client
                do {
                   try {
                      message =  input.readInt();
                      if (message==rnum){output.writeUTF("SERVER>>> YOU WON: MAGIC NUMBER IS: " +rnum);}
                       else {output.writeUTF("SERVER>>> YOU LOSE: MAGIC NUMBER IS: " +rnum);}
                      display.append( "\n\n" +"PLAYER " + clientNumber + " SELECTED NUMBER " + message );
                      display.setCaretPosition( display.getText().length() );
                   // process problems reading from client
                   catch ( IOException ioException ) {
                      display.append( "\nUnknown object type received" );
                } while ( message!=-1 );
                display.append( "\nClient terminated connection" );
                display = null;
             // close streams and socket
             finally {
                try {
                   output.close();
                   input.close();
                   connection.close();
                // process problems with I/O
                catch ( IOException ioException ) {
                   ioException.printStackTrace();
                clients.remove( this );
          }  // end method run
        

    I just implemented something like this so I know what you are trying to do.
    Basically TimerTask is an Abstract class, which means you can't make an instance of it. So TimeTask t = new TimeTask() won't work. Instead what you need to do is make your own class that extends TimerTask. You then need to implement the run() method which is abstract in TimerTask.
    This sounds complicated at first, but it is very easy.
    This is my DelayTimerTask:
    import java.util.TimerTask;
    *Author: Jon Parise
    *email: [email protected]
    public class DelayTimerTask extends TimerTask{
        private boolean timeExpired = false;
        /** Creates a new instance of DelayTimerTask */
        public DelayTimerTask() {
            timeExpired =false;
        public void run(){
            timeExpired =true;
        public boolean isExpired(){
            return this.timeExpired;
    }All this class does is set a flag when it is run.
    The Timer class schedules a TimerTask, in this case a DelayTimer. When the scheduled time comes, everything in run is executed, which in this case sets the flag.
    To schedule the task do this:
    Timer delayTimer = new Timer();
    DelayTimerTask delayTimerTask = new DelayTimerTask();
    delayTimer.schedule(delayTimerTask,5000);
    while(!delayTimerTask.isExpired()){
         //DoSomething Here
    }This will create a new delayTimer, and then schedule it to go off in 5 seconds(5000 millaseconds). When it goes off isExpired will become true and break you out of the loop.
    Hope this helps,
    Jon

  • Is there any way to set up a childs iPhone so the thing won't work or text during their school class time but work at lunch, brunch before and after school?

    I marked this as a question but really its a plea for a feature. I think if I could lock out the phone's capablity to text / call while someone was in class, I would buy one for my kids, but until that happens they are not getting one. Unless there IS a way to do this...
    Thanks
    J

    Hi. I doubt there is an existing App, but I imagine it would make the lives of teachers and school staff a little easier. You can make suggestions to Apple at the link below.
    http://www.apple.com/feedback/iphone.html
    Stedman

  • Timer Class in jsdk 1.4 w2000 doesn't compile

    Since this is based in the tutorial, shouldn't be a big deal but I spent the whole day looking for a solution. Please help!
    The tutorial presents this program:
    //1.3
    import java.util.timer;
    public class Problem {
    public static void main(String[] args) {
    final Timer timer = new Timer();
    timer.schedule(new TimerTask(), 5000);
    System.out.println("In 5 seconds this application will exit. ");
         public class TimerTask implements Timer {
    public void run() {
    System.out.println("Exiting.");
    timer.cancel();
    My problem starts because java.util doesn't have the timer class:
    Problem.java:2: Class java.util.timer not found in import.
    import java.util.timer;
    ^
    Now, JSDK 1.4 doesn't have timer as a package, but as a class, nevertheless, the instruction:
    import java.util.*; // instead of java.util.Timer
    doesn't compile because
    Problem.java:10: Interface Timer of inner class Problem. TimerTask not found.
    Problem.java:6: Class Timer not found in type declaration.
    I think Timer should be expressed as abstract, but how?
    I'm new in Java and feel a little frustrated...

    >
    ProblemSolved.java:3: Class java.util.Timer not found
    in import.
    import java.util.Timer;
    ^
    1 error
    Then you are not using java 1.3. You are using something before that.
    for the Timer and
    javac IteratorDemo.javaIteratorDemo.java:1: Interface java.util.Iterator of
    class IteratorDemo not foun
    d.
    public class IteratorDemo implements
    java.util.Iterator {
    ^
    1 error
    And this suggests that you are using something before 1.2.
    Just a thought...
    Windows comes with the MS version of java, which matches something like 1.1.6. It is in the path. So does you path put the jdk path first or last?

  • Win32 - timer class error

    heres my timer class:
    class Timer
    private:
    UINT_PTR timerid=0;
    unsigned int intInterval=0;
    HWND timerwindow=NULL;
    void TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime)
    timerprocedure();
    static void CALLBACK _TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime )
    reinterpret_cast<Timer*>(idEvent)->TimerProc(hwnd,uMsg,idEvent,dwTime);
    public:
    std::function<void()> timerprocedure=NULL;
    property<unsigned int> Interval
    Get(unsigned int)
    return intInterval;
    Set(unsigned int uintInterval)
    intInterval = uintInterval;
    if (intInterval==0 && timerid!=0)
    KillTimer(timerwindow,timerid);
    void Start()
    if(timerid!=0)
    KillTimer(timerwindow,timerid);
    timerwindow=GetForegroundWindow();
    timerid=SetTimer( timerwindow,reinterpret_cast<UINT_PTR>(this),(UINT)intInterval,&Timer::_TimerProc);
    SetWindowText(timerwindow,to_string(GetLastError()).c_str());
    void Stop()
    KillTimer(timerwindow,timerid);
    timerid=0;
    ~Timer()
    KillTimer(timerwindow,timerid);
    yesterday was working. and i was seen 1 bug, stoped sometimes when the window loses the focus.
    but now the GetLastError() give 6: invalid handle.
    these don't makes sence to me :(
    is there another timer that don't need the HWND?(for avoid future problems)

    On 2/15/2015 1:29 PM, Cambalinho wrote:
    i had created them on window procedure.
    What is "them"? Created how? What do you mean by "on window procedure".
      and that timer class is another timer. what i mean is the timer
    WM_TIMER and my timer class aren't created
    The only SetTimer call in the code you've shown is the one you admit is failing. To the extent a problem exists, it must be in the code you haven't shown. Lacking mind-reading abilities, I'm afraid I'm unable to assist you any further.
    so maybe the message loop is crazy :(
    Looks OK to me. Well, it may call IsDialogMessage with a NULL handle, but I believe this should cause IsDialogMessage to return FALSE and then the normal message dispatch takes place. Just to be sure, you may want to make it
    [code]
    if (!FormActivated || !IsDialogMessage(FormActivated, &msgEvents))
    [code]
    Igor Tandetnik
    my problem is: no timer is executed :(
     and i don't understand why. only the handle been invalid :(
    see my form\window window procedure:
    void setParent(HWND parent=GetDesktopWindow())
    if (hwnd==NULL)
    WNDCLASSEX FormClass;
    char classname[20]="Form";
    sprintf(classname,"%s",strCaption.c_str());
    HINSTANCE mod = (HINSTANCE)GetModuleHandle(NULL);
    FormClass.cbSize = sizeof(WNDCLASSEX);
    FormClass.style = CS_HREDRAW | CS_VREDRAW;
    FormClass.lpfnWndProc = WndProcForm;
    FormClass.cbClsExtra = 0;
    FormClass.cbWndExtra = 0;
    FormClass.hInstance = mod;
    FormClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    FormClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    FormClass.hbrBackground = (HBRUSH)((COLOR_WINDOW)+1);
    FormClass.lpszMenuName = NULL;
    FormClass.lpszClassName = classname;
    FormClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
    // register the new window class
    RegisterClassEx(&FormClass);
    hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, classname, strCaption.c_str(),WS_OVERLAPPEDWINDOW | WS_TABSTOP,
    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent, NULL, mod, this);
    if (hwnd == NULL)
    MessageBox(NULL, "Can't create the control", "error", MB_OK);
    else
    SetParent(hwnd,parent);
    ShowWindow(hwnd, SW_NORMAL);
    InvalidateRect(hwnd,NULL,true);//i add these line for fix that
    UpdateWindow(hwnd);
    clrBackColor =GetDCBrushColor(GetDC(hwnd));
    clrTextColor = GetTextColor(GetDC(hwnd));
    //window procedure:
    static LRESULT CALLBACK WndProcForm(HWND HandleWindow, UINT msg, WPARAM wParam, LPARAM lParam)
    static POINT PreviousLocation, Location;
    static bool Tracking = false;
    static MouseButtons MBButtons;
    static bool blControl = false;
    static bool blShift = false;
    static bool blResize = false;
    static int KeyDownCount=0;
    static int keyboard[256];
    static int xPos = 0;
    static int yPos = 0;
    static UINT_PTR timerid=0;
    static UINT_PTR KeyBoardTimer=2;
    static UINT_PTR JoystickTimer=1;
    static bool blnDrag = false;
    static bool KeyPressed=false;
    static HMENU menuhandle=NULL;
    HDC hdcimage = CreateCompatibleDC(NULL);
    HBITMAP hbitmap=NULL;
    //UINT JoystickCount =0;
    form *inst = (form *)GetWindowLongPtr(HandleWindow, GWLP_USERDATA);
    if(inst!=NULL && inst->Create!=NULL )
    static bool i=true;
    if(i==true)
    i=false;
    RECT a;
    GetWindowRect(inst ->hwnd,&a);
    inst -> Create(a.left, a.top);
    //Working with messages
    switch(msg)
    case WM_NCCREATE:
    CREATESTRUCT *p = (CREATESTRUCT *)lParam;
    inst = (form *)p->lpCreateParams;
    SetWindowLongPtr(HandleWindow, GWLP_USERDATA, (LONG_PTR)inst);
    inst->hwnd = HandleWindow;
    break;
    case WM_ACTIVATE:
    if (wParam==WA_INACTIVE) // becoming inactive
    FormActivated = NULL;
    else // becoming active
    FormActivated = inst->hwnd;
    return 0;
    break;
    case WM_DRAWITEM:
    DRAWITEMSTRUCT *test=(DRAWITEMSTRUCT*) lParam;
    SendMessage(test->hwndItem, WM_DRAWITEM, wParam, lParam);
    break;
    case WM_USER + 1:
    if(lParam==WM_RBUTTONUP)
    POINT pCursor;
    GetCursorPos(&pCursor);
    HMENU test=GetSubMenu(GetMenu(HandleWindow),0);
    SetForegroundWindow(HandleWindow);
    TrackPopupMenu(test, TPM_LEFTBUTTON | TPM_RIGHTALIGN, pCursor.x, pCursor.y, 0, HandleWindow, NULL);
    PostMessage(HandleWindow, WM_NULL, 0, 0);
    break;
    case WM_ERASEBKGND:
    return DefWindowProc(HandleWindow, msg, wParam, lParam);
    break;
    case WM_CTLCOLORSTATIC:
    return DefWindowProc(HandleWindow, msg, wParam, lParam);
    break;
    case WM_CREATE:
    if(WindowMain == NULL || WindowMain ==GetDesktopWindow())
    WindowMain = HandleWindow;
    SetTimer(inst->hwnd,JoystickTimer,150,NULL);
    SetTimer(inst->hwnd,KeyBoardTimer,150,NULL);
    SendMessage((HWND)lParam , WM_CREATE, wParam, lParam);
    break;
    case WM_SIZE:
    RECT a;
    GetWindowRect(inst->hwnd,&a);
    InvalidateRect(inst->hwnd, &a,true);
    inst->Resize();
    break;
    //for get the menu click event
    //i'm using menu notifications
    case WM_MENUCOMMAND:
    MENUITEMINFO menuInfo;
    menuInfo.cbSize = sizeof(MENUITEMINFO);
    menuInfo.fMask=MIIM_DATA;
    if(GetMenuItemInfo((HMENU)lParam,(UINT) wParam, TRUE, &menuInfo )!=0)
    Menu *mMenu = (Menu *) menuInfo.dwItemData;
    if(mMenu!=NULL)
    mMenu->Click();
    menuhandle=NULL;
    break;
    case WM_TIMER:
    if (wParam == timerid)//for mouse stoped and it's working normaly
    PreviousLocation = Location;
    GetCursorPos(&Location);
    if ((Location.x == PreviousLocation.x) && (Location.y == PreviousLocation.y))
    KillTimer(inst->hwnd, timerid);
    inst->MouseStoped();
    else if(wParam==KeyBoardTimer)
    static bool KeyDown=false;
    static int RepeatKeyDown;
    int key[256];
    GetKeyBoardKeyState(key);
    static int key2[256];
    if(key[AnyKey]==1 && KeyDown==false)
    KeyDown=true;
    RepeatKeyDown++;
    GetKeyBoardKeyState(key2);
    inst->SysKeyDown(key,RepeatKeyDown);
    else if(key[AnyKey]==0 && KeyDown==true)
    KeyDown=false;
    inst->SysKeyUp(key2,RepeatKeyDown);
    RepeatKeyDown=0;
    else if(wParam==JoystickTimer)
    JOYINFOEX b;
    b.dwSize=sizeof(JOYINFOEX );
    b.dwFlags=JOY_RETURNALL;
    //cicle all possible joysticks
    for (int i=0; i<16; i++)
    int direction=0;
    if(joyGetPosEx(i,&b)!= JOYERR_NOERROR) //if theres any error then continue to next joystick
    if(i==0)
    inst->Joystick(-1, -1,-1);
    else
    inst->Joystick(0, -1,-1);
    break;
    long h =b.dwButtons;
    //testing the directions
    //will be 8 directions(inclued diagonals)
    if (b.dwXpos == 0 && b.dwYpos ==65535)
    direction=5;
    else if (b.dwXpos == 65535 && b.dwYpos ==0)
    direction=6;
    else if (b.dwXpos == 65535 && b.dwYpos ==65535)
    direction=7;
    else if(b.dwXpos == 0 && b.dwYpos ==65535)
    direction=8;
    else if (b.dwXpos == 0)
    direction=1;
    else if (b.dwXpos == 65535)
    direction=2;
    else if (b.dwYpos == 0)
    direction=3;
    else if (b.dwYpos == 65535)
    direction=4;
    inst->Joystick(i, direction,h);
    break;
    these don't make sence to me :(

  • A Time Class...

    I decided to try to do this program i found in one of my java books.
    it asked us to
    Create a Class called Time
    3 private ints called Seconds, hours, minutes
    add 2 sets of times.
    Display Data
    This is the program i came up with!.. I actually did this all on my own (not saying much to you.. but i am happy :) )
    public class Time
      private int hours;
      private int minutes;
      private int seconds;
      public Time()
        hours = 0;
        minutes = 0;
        seconds = 1;
      public Time addTime (Time someTime)
       Time theAdd = new Time();
       theAdd.seconds = this.seconds + someTime.seconds;
       if (theAdd.seconds >60)
         this.minutes = this.minutes + 1;
         theAdd.seconds = theAdd.seconds -60;
       theAdd.minutes = this.minutes + someTime.minutes;
       if (theAdd.minutes > 60)
         this.hours =  this.hours +1;
         theAdd.minutes = theAdd.minutes -60;
        theAdd.hours = this.hours + someTime.hours;
        System.out.println ("Time is "+theAdd.hours+":"+theAdd.minutes +":"+theAdd.seconds);
        return theAdd;
        public  void setTime(int Sec, int Min, int Hour)
          seconds = Sec;
          minutes = Min;
          hours = Hour;
        public void display()
          System.out.println (this.hours+":"+this.minutes+":"+this.seconds);
        public class themain
          public static void main (String []args)
            Time firstTime = new Time();
            Time secondTime = new Time();
            int sec; int min; int hour;
            firstTime.setTime(20, 30, 2);
            secondTime.setTime(50, 50, 3);
            firstTime.display();
            secondTime.display();
            firstTime.addTime(secondTime);
         anyone have anyways i can imrpove on it?
    I followed the instructions i got bfore, and didnt do everything in the main! I am excited as this is the first java program i did on my own!
    Oh well.. its very basic so who knows!
    How you think i can improve it?
    Thanks!

    Personally I'd find it more natural to initialize the value of a new Time object to 0 seconds, rather than to 1 second. And I would allow for the possibility of negative times. That means that your code like this:if (theAdd.seconds >60)...has to be followed by more code like this:if (theAdd.seconds <-60)...In fact the "normalization" you are doing with that code may need to be rewritten, or you may end up with Time objects that contain 5 minutes and -30 seconds.

  • Problem with subclass and super class

    here is the things i wanted to do
    /*Write a method that takes the time as three integer arguments (hours, minutes and seconds),
    and returns the number of seconds since the last time it was twelve o'clock.
    Write a program that uses this method to calculate the amount of time in seconds between two times,
    assuming both are within one twelve hour cycle of a clock.
    here is a class to find the last time closes to 120'clock in sec.
    import java.io.*;
    public class Timer {
         int converter = 60;
         int secinTwelveHour = 43200;
         int converter2 = 12;
    public int timerTime (int hour, int min, int sec){
              int totalSec = 0;
              //Finding the time
              if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour <= 11){
                   //find last 12 o'Clock
                   hour = converter2 + hour;
                   //change to sec time
                   totalSec = (hour * converter * converter) + (min * converter) + sec;
              }else{     
         if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour >= 12){
                   //find last 12 o'Clock in sec
                   totalSec = ((hour * converter * converter) + (min * converter) + sec) - secinTwelveHour;
         }else{
              return -1;
    }//End of return -1      
              }//End of first else statment
         return totalSec;     
         }//End of timerTimer
    }//End of Program     
    and here is the super class which uses the class aboved
    import java.io.*;
    public class FindTime {
    public int find2Time (int totalSec1, int totalSec2){
              int timeSec = 0;
              if(Timer.totalSec1 > Timer.totalSec2)
              timeSec = Timer.totalSec1 - Timer.totalSec2;
              else
              timeSec = Timer.totalSec2 - Timer.totalSec1;
         return timeSec;     
         }//End of find2Time
    public static void main( String [] arg){
         // Construct an instance of the Timer class
              Timer timerClass = new Timer();
              // Make a couple of calls of the method
              int totalSec1 = timerClass.timerTime(12, 3, 45);
              int totalSec2 = timerClass.timerTime(14, 23, 60);
              timeSec1 = find2Time (totalSec1, totalSec2)
              // Now print the values we got back
              System.out.println("Last closes Sec to 12 o'clock" + totalSec1);
              System.out.println("Last closes sec to 12 o'clock" + totalSec2);
              System.out.println("Last closes sec to 12 o'clock" + timeSec);
         }//End of main method
    }//End of Program     
    Now i'm having program with the compliing can anyone help me out like tell me what i'm doing wrong and give me a bit of a code so that i can have a push start
    thanks you

    Does this do what you want? It is in two seperate classes.
    import java.io.*;
    public class FindTime {
    public static void main( String [] arg){
    int timeSec = 0;
    // Construct an instance of the Timer class
         Timer timerClass = new Timer();
         // Make a couple of calls of the method
         int totalSec1 = timerClass.timerTime(12, 3, 45);
         int totalSec2 = timerClass.timerTime(14, 23, 60);
         timeSec = java.lang.Math.abs(totalSec1-totalSec2);
         // Now print the values we got back
         System.out.println("Last closes Sec to 12 o'clock " + totalSec1);
         System.out.println("Last closes sec to 12 o'clock " + totalSec2);
         System.out.println("Last closes sec to 12 o'clock " + timeSec);
         }//End of main method
    }//End of Program
    import java.io.*;
    public class Timer {
    int converter = 60;
    int secinTwelveHour = 43200;
    int converter2 = 12;
    public int timerTime (int hour, int min, int sec){
         int totalSec = 0;
         //Finding the time
         if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour <= 11){
         //find last 12 o'Clock
         hour = converter2 + hour;
         //change to sec time
         totalSec = (hour * converter * converter) + (min * converter) + sec;
         } else {
         if (hour > 0 && hour <= 24 && min > 0 && min <=60 && sec > 0 && sec <= 60 && hour >= 12){
         //find last 12 o'Clock in sec
         totalSec = ((hour * converter * converter) + (min * converter) + sec) - secinTwelveHour;
         } else {
              return -1;
         }//End of return -1
    }//End of first else statment
    return totalSec;
    }//End of timerTimer
    }//End of Program

  • How to get a int value from another class method?

    Hi,
    how can I get a value of another class method variable value.
    example,
    class elist
            int a;
         ArrayList<Event> eventArray;
         void addEvent(Event e);
         Event getEvent(int index);
         void removeEvent(int index);
         void orderEventByTime();
    interface Event
         void Command();
    class servo implements Event
         String ip;
         int time = 10;
         void Command();
    class servo_2 implements Event
         String ip;
         int time = 20;
         void Command();
    [\code]
    I want to get the time value in elist variable a; 
    and want to compare each class time?.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi,
    1) this foum provides means to format/tag code, no need to manually add -tags
    2) by default, classname start with a capital letter, method names with a lower case letter
    3) where do you want to get the time value to Elist.a? During addEvent()?
    4) what do you want to do with the time value of each event? Sum all values up to make a an overall sum?
    5) where do you want to compare the time value(s)?
    To put it in one sentence: please be more specific with your description and answer.
    Bye.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to use object of class in Label?

    I have defined a class "time" which runs time for 30 minutes.Now, I want to use this time in Label so that it keep running for 30mins but I am not able to pass the object in Label.

    Of course being aware that this may cause other
    difficulties if you are running a multi-threadedapp.
    SwingUtilities.invokeLater() may be required inthat
    case.I've never really been clear on which of these update
    routines should, or should not be on the dispatcher
    thread. A quick look at the source of JLabel.setText,
    for example, shows that it calls repaint on itself to
    change the presentation of text, and repaint
    shouldn't require to be on the dispatcher thread,
    since it simply adds the paint request to the TODO
    list.That makes sense, but experience doesn't bear it out... I've had deadlocks where the only thing being updated was the text of a label. Perhaps there is something else going on.

  • Thread timer problem

    I am making a cards game that requires turns. If a player doesnt respond within say 5 minutes , he must be logged off.
    I have class that keeps track of the turn of each player
    . What I want is a process(thread) that is passed the turn and starts a timer . If the turn doesnt change for say 5 minutes (I can log off the player I am using rmi )
    and if it changes ( I pass the turn each time it changes to the thread) , I want to restart the timer.
    how can I do this?

    My code works this way:
    You make a class that implements TimerListener. This means it will get a method that is called TimerExpired().
    Then you create a Timer object. You register the TimerListener with the Timer by calling the registerTimerListener() method. Now that listener will receive an event each time the Timer expires.
    Whenever you set the timer (useing the setTimer() method), the timer will wait for the amount of time you specify. After that it will call the TimerExpired() method of the object you registered as a timer.
    Simple as that...
    If that doesn't work for you then you will have to add more information about your application. What is it you wait for? How do you do when you wait?
    Here is an update of the class that allows you to reset the timer.public class Timer extends Thread {
      private TimerListener timerListener = null;
      private boolean timerIsSet = false;
      private long wakeUpTime = 0;
      private long timeToWait = 0;
      public Timer(){
        this.start();
      public void run(){
        while(true){
          // Loop for when the timer is inactive.
          synchronized(this){
            while(!timerIsSet){
              try{
                this.wait();
              catch(InterruptedException e){
          // Loop for when the timer is set.
          synchronized(this){
            while(timerIsSet){
              timerIsSet = false;
              try{
                timeToWait = wakeUpTime - System.currentTimeMillis();
                if(timeToWait > 0){
                  this.wait(timeToWait);
              catch(InterruptedException e){
          if(wakeUpTime != 0 && timerListener != null){
            timerListener.timerExpired(new TimerEvent());
      public void registerTimerListener(TimerListener timerListener){
        this.timerListener = timerListener;
       * Set the timer to expire in t milliseconds.
       * If t is less than or equal to 0 the timer will be reset
       * and no event will be sent until setTimer() is called again.
      public synchronized void setTimer(long t){
        if(t <= 0){
          wakeUpTime = 0;
        else{
          wakeUpTime = (t + System.currentTimeMillis());
          timerIsSet = true;
        this.notifyAll();
    }/Michael

  • Using Time.expression in a custom library

    Hello All,
    I am trying to write a piece of code in a custom library. Upon trying to save the code, it tries to compile and kicks out a message "...cannot resolve symbol symbol : class Time location..."
    Does any one know which class to import in order to use the Time function?
    I have already imported  com.redwood.scheduler.api.date.*;
    Thanks
    Daniel

    Hello,
    The code in a library works slightly different then the expressions.
    You can use:
      DateTimeZone myDate = DateTimeZone.expressionNow("add 1 day");
    regards Gerben
    Edited by: G. Blom on Feb 24, 2011 12:49 PM

  • Windows File Time stamp

    Hello!
    From my understanding there is a File class which has several methods e.g to get file name. The problem i am having is I am trying to implement a simple program which looks at the time file stamp and output the creation, access and modified times of a file; so far I have been able to retrieve the last modified time of a file but not the access and creation times. How is this done? below there is code to retrieve last modified time:-
    ===================================================
    package timestamp;
    import java.io.*;
    import java.util.*;
    public class Main {
    public static void main(String[] args)throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter file or directory name : ");
    File filename = new File(in.readLine());
    // check to see if its a directory
    if (filename.isDirectory()){
    // check to see if its a file
    if (filename.exists()){
    long t = filename.lastModified();
    // get a directory name
    System.out.println("Directory name : " + filename.getName());
    System.out.println("Directory modification date and time : " + new Date(t));
    else{
    System.out.println("Directory not found!");
    System.exit(0);
    else{   // check to see if the file name exists
    if (filename.exists()){
    long t = filename.lastModified();
    System.out.println("File name : " + filename.getName());
    System.out.println("File modification date and time : " + new Date(t));
    else{
    System.out.println("File not found!");
    System.exit(0);
    }

    Hi! thanks for the response I have written the code to retrieve the creation, access and modified times using Run exec (). A user enters file or directory name and idealy it should output those times. When i run the program I get IOException error=2..... a lot of articles online suggest the error means that the files is not found but the file I have specify does exist unless the my coding is wrong. Any suggestions:
    C:\>java Times
    Enter file or directory name:
    C:\Dev-C++
    exception happened :
    java.io.IOException: CreateProcess: "dir \tc" "dir /ta" "dir /twC:\Dev-C++" error=2
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Times.main(Times.java:23)
    source code
    import java.io.*;
    public class Times {
    public static void main(String args[]) {
    String s = null;
    try {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter file or directory name: ");
    File filename = new File(in.readLine());
         // run windows command in conjuction with entered file/directory name
         // creation time "dir /tc"
         // access time "dir /ta"
         // modifed time "dir /tw"
         String [] times={"dir /tc", "dir /ta" , "dir /tw" + filename};
    Process p= Runtime.getRuntime().exec(times);
    //Process p= Runtime.getRuntime().exec("dir /tc" + "dir /ta" + "dir /tw" + filename);
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    // read the output from the command
    System.out.println("The output:\n");
    while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    System.exit(0);
    catch (IOException e) {
    System.out.println("exception happened : ");
    e.printStackTrace();
    System.exit(-1);
    }

  • Timer in Applet - Source code available

    Hello,
    I have this timer class which works. How do I include it in an Applet so that my applet
    displays time?
    Thanks
    Mathew
    import java.util.*;
    public class TimeTest implements Runnable
         Calendar time;
         int hour, minute, second;
         Thread thread = null;
         public TimeTest()
              time = Calendar.getInstance();
              hour = time.get(Calendar.HOUR_OF_DAY);
              minute = time.get(Calendar.MINUTE);
              second = time.get(Calendar.SECOND);
              if(thread == null)
                   thread = new Thread(this);
                   thread.start();
         public void run()
              try
                   Thread t = Thread.currentThread();
                   while(thread == t)
                        thread.sleep(1000);
                             second++;
                        if(second > 59)
                             minute++;
                        if(minute>59)
                             hour++;
                        formatTime();
                   while(thread != t)
                        thread.suspend();
              catch(Exception e)
                   e.printStackTrace();
         public void formatTime()
              second = (second > 59? 0 : second);
              minute = (minute > 59? 0 : minute);
              hour = (hour > 23? 0 : hour);
              System.out.println(hour+":"+minute+":"+second);
         public static void main(String[] args)
              new TimeTest();
         public void stop()
              thread.stop();
    }

    How about this:
    import java.util.*;
    import java.text.*;
    import java.awt.event.*;
    public class Timer 
         javax.swing.Timer timer;
         SimpleDateFormat  timef = new SimpleDateFormat("HH:mm:ss");
    public Timer()
         timer = new javax.swing.Timer(1000, new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String s = timef.format(new Date(System.currentTimeMillis()));
                   System.out.println(s);
         timer.start();
    public static void main (String[] args) 
         new Timer();
         while (true){}
    }

  • SETTING FIELD IN ANOTHER CLASS

    I have 3 classes: class1 extends Jpanel, class2 extends Jpanel, class3 extends JFrame. What I am trying to do is set the textfields in class1 from class2 according to user input: user enters an ID and presses a button (in another frame: class4) and data relating to that ID e.g. name, number... is retrieved from the server and then the fields in class1 are set to these values from class2. I have the following coding
    class 1
    JTextfield nameField = new JTextField()
    class1 constructor(
    panel.add(nameField)
    class2
    class1 c1 = new class1()
    c1.clTextField.setText(...)
    panel.add(c1)
    class 3 constructor
    panel.add(class2Object);
    when the user enters an ID (in class4)and presses enter the correct data is displayed. However when I close down the class3 frame and enter another ID the frame gets displayed but all the textFields have gone missing????????
    p.s. what is the difference between creating a new object and invoking it on the textfield e.g.(in class1)
    class2 c2 = new class2
    c2.textFieldInClass2
    and stating the textfield as a static string in class2 and then just invoking class2Name on it in class1 e.g.
    class2Name.textfield

    import java.util.Date;
    public class Time {
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
    Date utilDate;
    java.sql.TimeStamp sqlDate;
    String stringDate;
    public Time(){
    utilDate = new Date();
    stringDate = formatter.format(utilDate)
    sqlDate = new java.sql.TimeStamp(utilDate.getTime)
    stringDate can be displayed in frame. sqlDate is entered into the server. you can have the simpledateformat according to the format date you require

  • How to control the time.

    I 'am a Java beginner but already know OOP.
    I would develop an alarm which helps me to remember my appointment of the day, i.e. I schedule at the 17:00 the dentist appointment, so my application alrm me.
    I need a class that monitors the clock fo my PC and when it 's 17:00 my application start.
    I thought to use the class Timer (in particular the scheduler method).
    Thank you in advance.

    You can use the Timer or TimerTask and schedule a task every 1 minute.
    In the task, you have to
    1. Use getHours() to get the current hour.
    2. Compare it with the alarm time.
    If equal, set off the alarm..

Maybe you are looking for

  • How to send HTML DOM to Servlet?

    How to send HTML DOM to Servlet?

  • Bdc for MM01 with classification view

    Hi all, I need to create materials using mm01 with classification view. since there is no bapi supporting this view, i am ding by bdc. The problem is in classification view once i give the class type and name a screen pops with caption characteristic

  • What I think of itunes

    They make stylish products.. BUT!! there is quite obviousley a problem with the new upgraded itunes, (opening and connecting to the store).... most people are sitting around thinking "what next??".. what are we ment to do??... there are no actual ans

  • Can subreports use same selection parameter(s) as main report?

    Hi, Is it possible to create subreports that use the selection selection parameter(s) as the main report. And if so, would the user need to make their selections twice, or just once when they open the report? Thanks, Jon

  • Fetch records at runtime

    Hi, I have a query.Lets say my cursor fetch 1000 records. my requirement is i like to pass 2 parameters at runtime which will decide the starting point and total records to be fetch out of those 1000 records.Lets say i like to retrieve 50 records sta