Hey,
I was just wondering how hard it would be to take a program that already has the time hardcoded into it (it is a countdown program) and make it so that the user can input the amount of time they want? This is the code that I have now, and when the program starts, I want it to ask how long the program should run.
package countdowntimer;
import java.awt.event.*;
import javax.swing.*;
public class CountdownTimer extends JFrame implements ActionListener, Runnable
{
private long startTime;
private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss : SSS");
private final JButton startStopButton = new JButton("Start/Stop");
private Thread updater;
private boolean isRunning = false;
private final Runnable displayUpdater = new Runnable()
{
public void run()
{
displayElapsedTime(CountdownTimer.this.startTime - System.currentTimeMillis());
}
};
public void actionPerformed(ActionEvent ae)
{
if(isRunning)
{
long elapsed = startTime - System.currentTimeMillis();
isRunning = false;
try
{
updater.join();
// Wait for updater to finish
}
catch(InterruptedException ie) {}
displayElapsedTime(elapsed);
// Display End Result
}
else
{
startTime = 2*60*1000+System.currentTimeMillis();
isRunning = true;
updater = new Thread(this);
updater.start();
}
}
private void displayElapsedTime(long elapsedTime)
{
startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
}
public void run()
{
try
{
while(isRunning)
{
SwingUtilities.invokeAndWait(displayUpdater);
Thread.sleep(50);
}
}
catch(java.lang.reflect.InvocationTargetException ite)
{
ite.printStackTrace(System.err);
// Prints Error - shouldn't ever happen
}
catch(InterruptedException ie) {}
// Ignore and return!
}
public CountdownTimer()
{
startStopButton.addActionListener(this);
getContentPane().add(startStopButton);
setSize(100,50);
setVisible(true);
}
public static void main(String[] arg)
{
new CountdownTimer().addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Thanks for all the help!
Bobby