Issues: Creating a very accurate Swing Timer - java

In order to make SwingTimer accurate, I like the logic and example suggested by #Tony Docherty
On CR. Here is the Link.
In order to highlight the given words, again and again, there is always a few microsecond delays. If I have words to highlight say: "hello how are" and the values for each word are (delays): 200,300,400 ms respectively, then the actual time taken by the timer is always more. Say instead of 200 ms, it takes 216 ms. Like this, if I have many words..in the end, the extra delay is noticeable.
I have to highlight each letter say: 'h''e''l''l''0' each should get 200/length(i.e 5) = 40 ms approx. Set the delay after each letter.
My logic is, take the current time say startTime, just before starting the process. Also, calculate the totalDelay which is totalDelay+=delay/.length().
Now check the condition: (startTime+totalDelay-System.currentTime)
if this is -ve, that means the time consumption is more, so skip the letter. Check till there is a positive delay.This means I am adding the timings till now, and overcheck it with the difference in the time taken by the process when it got started.
This may result into skipping to highlight the letters.
But something is wrong. What, it’s difficult for me to make out. It's some problem with the looping thing maybe. I have seen it is entering the loop (to check whether the time is -ve ) just twice. But this should not be the case. And I am also not sure about setting up my next delay. Any ideas?
Here is an SSCCE:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Reminder {
private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
private static final String[] WORDS = TEXT.split(" ");
private JFrame frame;
private Timer timer;
private StyledDocument doc;
private JTextPane textpane;
private int[] times = new int[100];
private long totalDelay=0,startTime=0;
private int stringIndex = 0;
private int index = 0;
public void startColoring() {
times[0]=100;times[9]=200;times[10]=200;times[11]=200;times[12]=200;
times[1]=400;times[2]=300;times[3]=900;times[4]=1000;times[5]=600;times[6]=200;times[7]=700;times[8]=700;
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent)
{
doc.setCharacterAttributes(stringIndex, 1, textpane.getStyle("Red"), true);
stringIndex++;
try {
if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ")|| doc.getText(stringIndex, 1).equals("\n"))
{
index++;
}
if (index < WORDS.length) {
double delay = times[index];
totalDelay+=delay/WORDS[index].length();
/*Check if there is no -ve delay, and you are running according to the time*/
/*The problem is here I think. It's just entered this twice*/
while(totalDelay+startTime-System.currentTimeMillis()<0)
{
totalDelay+=delay/WORDS[index].length();
stringIndex++;
/*this may result into the end of current word, jump to next word.*/
if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ") || doc.getText(stringIndex, 1).equals("\n"))
{
index += 1;
totalDelay+=delay/WORDS[index].length();
}
}
timer.setDelay((int)(totalDelay+startTime-System.currentTimeMillis()));
}
else {
timer.stop();
System.err.println("Timer stopped");
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
};
startTime=System.currentTimeMillis();
timer = new Timer(times[index], actionListener);
timer.setInitialDelay(0);
timer.start();
}
public void initUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
doc = new DefaultStyledDocument();
textpane = new JTextPane(doc);
textpane.setText(TEXT);
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
panel.add(textpane);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
Reminder reminder = new Reminder();
reminder.initUI();
reminder.startColoring();
}
});
}
}
UPDATE:
For better understanding:
The EG given by #Tony Docherty :
Lets take the word "Test" and say it needs to be highlighted for 1 second, therefore each letter is highlighted for 250ms.
Doing things the way you originally, did meant that you set a timer for 250ms for each letter but if each cycle actually took 260ms and lets say the 'e' cycle took 400ms (maybe due to GC or something else using CPU cycles) by the end of the word you would have taken 180ms more than you should have. This error will continue to build for each word until the error is so large highlighting is no longer visually in sync.
The way I am trying, is rather than repeatedly saying this letter needs to be highlighted for x amount of time, calculate the time for each letter relative to the beginning of the sequence ie T = 250, e = 500, s = 750, t = 1000.
So to get the actual time delay you need to add the start time and subtract the current time. To run through the example using the timings I gave above:
StartTime Letter Offset CurrentTime Delay ActualTimeTaken
100000 T 250 100010 240 250
100000 e 500 100260 240 400
100000 s 750 100660 90 100
100000 t 1000 100760 240 250
So you should be able to see now that the timing for each letter is adjusted to take account of any overrun of time from the previous letter. Of course it is possible that a timing overrun is so great that you have to skip highlighting the next letter (or maybe more than 1) but at least I will remaining broadly in sync.
EDITED SSCCE
Update2
In first phase, I take the timings for each word. That is, when the user hits ESC key, the time is stored for a particular word (he does it as the song is played in background.) When the ESC key is pressed, the current word is highlighted and the time spent on the current word is stored in an array. I keep on storing the timings. When the user ends, now I would like to highlight the words as per the set timings. So here, the timing by the user is important. If the timings are fast, so is the highlighting of words or if slow, vice-versa.
New update: progress
The answers below have different logic, but to my surprise, they work more or less the same. A very very weird problem I have found out with all the logic (including mine) is that they seem to work perfectly for few lines, but after that they gain speed, that's also not slowly, but with a huge difference.
Also if you think I should think in a different way, your suggestions are highly appreciated.

I think that to do something like this, you need a Swing Timer that ticks at a constant rate, say 15 msec, as long as it's fast enough to allow the time granularity you require, and then trip the desired behavior inside the timer when the elapsed time is that which you require.
In other words, don't change the Timer's delay at all, but just change the required elapse times according to your need.
You should not have a while (true) loop on the EDT. Let the "while loop" be the Swing Timer itself.
To make your logic more fool proof, you need to check if elapsed time is >= needed time.
Again, don't set the Timer's delay. In other words, don't use it as a timer but rather as a poller. Have it beat every xx msec constantly polling the elapsed time, and then reacting if the elapsed time is >= to your need.
The code I'm suggesting would look something like so:
public void actionPerformed(ActionEvent actionEvent) {
if (index > WORDS.length || stringIndex >= doc.getLength()) {
((Timer)actionEvent.getSource()).stop();
}
currentElapsedTime = calcCurrentElapsedTime();
if (currentElapsedTime >= elapsedTimeForNextChar) {
setNextCharAttrib(stringIndex);
stringIndex++;
if (atNextWord(stringIndex)) {
stringIndex++; // skip whitespace
deltaTimeForEachChar = calcNextCharDeltaForNextWord();
} else {
elapsedTimeForNextChar += deltaTimeForEachChar;
}
}
// else -- we haven't reached the next time to change char attribute yet.
// keep polling.
}
For example, my SSCCE:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
public class Reminder3 {
private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
private static final String[] WORDS = TEXT.split(" ");
private static final int[] TIMES = { 100, 400, 300, 900, 1000, 600, 200,
700, 700, 200, 200, 200, 200 };
private static final int POLLING_TIME = 12;
private StyledDocument doc;
private JTextPane textpane;
private JPanel mainPanel = new JPanel();
private List<ReminderWord> reminderWordList = new LinkedList<ReminderWord>();
private Timer timer;
// private int stringIndex = 0;
public Reminder3() {
doc = new DefaultStyledDocument();
textpane = new JTextPane(doc);
textpane.setText(TEXT);
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
JPanel textPanePanel = new JPanel();
textPanePanel.add(new JScrollPane(textpane));
JButton startBtn = new JButton(new AbstractAction("Start") {
#Override
public void actionPerformed(ActionEvent arg0) {
goThroughWords();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(startBtn);
mainPanel.setLayout(new BorderLayout());
mainPanel.add(textPanePanel, BorderLayout.CENTER);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
}
public void goThroughWords() {
if (timer != null && timer.isRunning()) {
return;
}
doc = new DefaultStyledDocument();
textpane.setDocument(doc);
textpane.setText(TEXT);
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
int wordStartTime = 0;
for (int i = 0; i < WORDS.length; i++) {
if (i > 0) {
wordStartTime += TIMES[i - 1];
}
int startIndexPosition = 0; // set this later
ReminderWord reminderWord = new ReminderWord(WORDS[i], TIMES[i],
wordStartTime, startIndexPosition);
reminderWordList.add(reminderWord);
}
int findWordIndex = 0;
for (ReminderWord word : reminderWordList) {
findWordIndex = TEXT.indexOf(word.getWord(), findWordIndex);
word.setStartIndexPosition(findWordIndex);
findWordIndex += word.getWord().length();
}
timer = new Timer(POLLING_TIME, new TimerListener());
timer.start();
}
public JComponent getMainPanel() {
return mainPanel;
}
private void setNextCharAttrib(int textIndex) {
doc.setCharacterAttributes(textIndex, 1,
textpane.getStyle("Red"), true);
}
private class TimerListener implements ActionListener {
private ReminderWord currentWord = null;
private long startTime = System.currentTimeMillis();
#Override
public void actionPerformed(ActionEvent e) {
if (reminderWordList == null) {
((Timer) e.getSource()).stop();
return;
}
if (reminderWordList.isEmpty() && currentWord.atEnd()) {
((Timer) e.getSource()).stop();
return;
}
// if just starting, or if done with current word
if (currentWord == null || currentWord.atEnd()) {
currentWord = reminderWordList.remove(0); // get next word
}
long totalElapsedTime = System.currentTimeMillis() - startTime;
if (totalElapsedTime > (currentWord.getStartElapsedTime() + currentWord
.getIndex() * currentWord.getTimePerChar())) {
setNextCharAttrib(currentWord.getStartIndexPosition() + currentWord.getIndex());
currentWord.increment();
}
}
}
private static void createAndShowGui() {
Reminder3 reminder = new Reminder3();
JFrame frame = new JFrame("Reminder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(reminder.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ReminderWord {
private String word;
private int totalTime;
private int timePerChar;
private int startTime;
private int startIndexPosition;
private int index = 0;
public ReminderWord(String word, int totalTime, int startTime,
int startIndexPosition) {
this.word = word;
this.totalTime = totalTime;
this.startTime = startTime;
timePerChar = totalTime / word.length();
this.startIndexPosition = startIndexPosition;
}
public String getWord() {
return word;
}
public int getTotalTime() {
return totalTime;
}
public int getStartElapsedTime() {
return startTime;
}
public int getTimePerChar() {
return timePerChar;
}
public int getStartIndexPosition() {
return startIndexPosition;
}
public int increment() {
index++;
return index;
}
public int getIndex() {
return index;
}
public boolean atEnd() {
return index > word.length();
}
public void setStartIndexPosition(int startIndexPosition) {
this.startIndexPosition = startIndexPosition;
}
#Override
public String toString() {
return "ReminderWord [word=" + word + ", totalTime=" + totalTime
+ ", timePerChar=" + timePerChar + ", startTime=" + startTime
+ ", startIndexPosition=" + startIndexPosition + ", index=" + index
+ "]";
}
}

Okay so I have been looking at the some code (the code I posted in your last question about Karaoke timer)
Using that code I put up some measuring system using System.nanoTime() via System.out.println() which will help us to see what is happening:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class KaraokeTest {
private int[] timingsArray = {1000, 1000, 9000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};//word/letters timings
private String[] individualWordsToHighlight = {" \nHello\n", " world\n", " Hello", " world", " Hello", " world", " Hello", " world", " Hello", " world"};//each individual word/letters to highlight
private int count = 0;
private final JTextPane jtp = new JTextPane();
private final JButton startButton = new JButton("Start");
private final JFrame frame = new JFrame();
//create Arrays of individual letters and their timings
final ArrayList<String> chars = new ArrayList<>();
final ArrayList<Long> charsTiming = new ArrayList<>();
public KaraokeTest() {
initComponents();
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
jtp.setEditable(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
count = 0;
charsTiming.clear();
chars.clear();
for (String s : individualWordsToHighlight) {
for (int i = 0; i < s.length(); i++) {
chars.add(String.valueOf(s.charAt(i)));
//System.out.println(String.valueOf(s.charAt(i)));
}
}
//calculate each letters timings
for (int x = 0; x < timingsArray.length; x++) {
for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
individualWordsToHighlight[x] = individualWordsToHighlight[x].replace("\n", " ").replace("\r", " ");//replace line breaks
charsTiming.add((long) (timingsArray[x] / individualWordsToHighlight[x].trim().length()));//dont count spaces
//System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
}
}
Timer t = new Timer(1, new AbstractAction() {
long startTime = 0;
long acum = 0;
long timeItTookTotal = 0;
long dif = 0, timeItTook = 0, timeToTake = 0;
int delay = 0;
#Override
public void actionPerformed(ActionEvent ae) {
if (count < charsTiming.size()) {
if (count == 0) {
startTime = System.nanoTime();
System.out.println("Started: " + startTime);
}
timeToTake = charsTiming.get(count);
acum += timeToTake;
//highlight the next word
highlightNextWord();
//System.out.println("Acum " + acum);
timeItTook = (acum - ((System.nanoTime() - startTime) / 1000000));
timeItTookTotal += timeItTook;
//System.out.println("Elapsed since start: " + (System.nanoTime() - startTime));
System.out.println("Time the char should take: " + timeToTake);
System.out.println("Time it took: " + timeItTook);
dif = (timeToTake - timeItTook);
System.out.println("Difference: " + dif);
//System.out.println("Difference2 " + (timeToTake - dif));
//calculate start of next letter to highlight less the difference it took between time it took and time it should actually take
delay = (int) (timeToTake - dif);
if (delay < 1) {
delay = 1;
}
//restart timer with new timings
((Timer) ae.getSource()).setInitialDelay((int) timeToTake);//timer is usually faster thus the entire highlighting will be done too fast
//((Timer) ae.getSource()).setInitialDelay(delay);
((Timer) ae.getSource()).restart();
} else {//we are at the end of the array
long timeStopped = System.nanoTime();
System.out.println("Stopped: " + timeStopped);
System.out.println("Time it should take in total: " + acum);
System.out.println("Time it took using accumulator of time taken for each letter: " + timeItTookTotal
+ "\nDifference: " + (acum - timeItTookTotal));
long timeItTookUsingNanoTime = ((timeStopped - startTime) / 1000000);
System.out.println("Time it took using difference (endTime-startTime): " + timeItTookUsingNanoTime
+ "\nDifference: " + (acum - timeItTookUsingNanoTime));
reset();
((Timer) ae.getSource()).stop();//stop the timer
}
count++;//increment counter
}
});
t.setRepeats(false);
t.start();
}
});
frame.add(jtp, BorderLayout.CENTER);
frame.add(startButton, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private void reset() {
startButton.setEnabled(true);
jtp.setText("");
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
JOptionPane.showMessageDialog(frame, "Done");
}
private void highlightNextWord() {
//we still have words to highlight
int sp = 0;
for (int i = 0; i < count + 1; i++) {//get count for number of letters in words (we add 1 because counter is only incrementd after this method is called)
sp += 1;
}
while (chars.get(sp - 1).equals(" ")) {
sp += 1;
count++;
}
//highlight words
Style style = jtp.addStyle("RED", null);
StyleConstants.setForeground(style, Color.RED);
((StyledDocument) jtp.getDocument()).setCharacterAttributes(0, sp, style, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new KaraokeTest();
}
});
}
}
The output on my PC is:
Started: 10289712615974
Time the char should take: 166
Time it took: 165
Difference 1
...
Time the char should take: 166
Time it took: 155
Difference 11
...
Time the char should take: 166
Time it took: 5
Difference 161
Stopped: 10299835063084
Time it should take in total: 9960
Time it took using accumulator of time taken for each letter: 5542
Difference: 4418
Time it took using difference (endTime-startTime): 10122
Difference: -162
Thus my conclusion is the Swing Timer is actually running faster than we expect as the code in the Timers actionPerformed will not necessarily take as long as the letters expected highlighting time this of course causes an avalanche effect i.e the faster/slower the timer runs the greater/less the difference will become and timers next execution on restart(..) will take be at a different time i.e faster or slower.
in the code do this:
//calculate start of next letter to highlight less the difference it took between time it took and time it should actually take
delay = (int) (timeToTake - dif);
//restart timer with new timings
//((Timer) ae.getSource()).setInitialDelay((int)timeToTake);//timer is usually faster thus the entire highlighting will be done too fast
((Timer) ae.getSource()).setInitialDelay(delay);
((Timer) ae.getSource()).restart();
Produces a more accurate result (maximum latency Ive had is 4ms faster per letter):
Started: 10813491256556
Time the char should take: 166
Time it took: 164
Difference 2
...
Time the char should take: 166
Time it took: 164
Difference 2
...
Time the char should take: 166
Time it took: 162
Difference 4
Stopped: 10823452105363
Time it should take in total: 9960
Time it took using accumulator of time taken for each letter: 9806
Difference: 154
Time it took using difference (endTime-startTime): 9960
Difference: 0

Have you considered java.util.Timer and scheduleAtFixedRate? You will need a little extra work to do stuff on the EDT, but it should fix the issue of accumulated delays.

ScheduledExecutorService tends to be more accurate than Swing's Timer, and it offers the benefit of running more than one thread. In particular, if one tasks gets delayed, it does not affect the starting time of the next tasks (to some extent).
Obviously if the tasks take too long on the EDT, this is going to be your limiting factor.
See below a proposed SSCCE based on yours - I have also slightly refactored the startColoring method and split it in several methods. I have also added some "logging" to get a feedback on the timing of the operations. Don't forget to shutdown the executor when you are done or it might prevent your program from exiting.
Each words starts colouring with a slight delay (between 5 and 20ms on my machine), but the delays are not cumulative. You could actually measure the scheduling overhead and adjust accordingly.
public class Reminder {
private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
"arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
"arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
"arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
"arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
"arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
private static final String[] WORDS = TEXT.split("\\s+");
private JFrame frame;
private StyledDocument doc;
private JTextPane textpane;
private static final int[] TIMES = {100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200, 200};
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
private int currentLetterIndex;
private long start; //for logging
public void startColoring() {
start = System.currentTimeMillis(); //for logging
int startTime = TIMES[0];
for (int i = 0; i < WORDS.length; i++) {
scheduler.schedule(colorWord(i, TIMES[i + 1]), startTime, TimeUnit.MILLISECONDS);
startTime += TIMES[i+1];
}
scheduler.schedule(new Runnable() {
#Override
public void run() {
scheduler.shutdownNow();
}
}, startTime, TimeUnit.MILLISECONDS);
}
//Color the given word, one letter at a time, for the given duration
private Runnable colorWord(final int wordIndex, final int duration) {
final int durationPerLetter = duration / WORDS[wordIndex].length();
final int wordStartIndex = currentLetterIndex;
currentLetterIndex += WORDS[wordIndex].length() + 1;
return new Runnable() {
#Override
public void run() {
System.out.println((System.currentTimeMillis() - start) + " ms - Word: " + WORDS[wordIndex] + " - duration = " + duration + "ms");
for (int i = 0; i < WORDS[wordIndex].length(); i++) {
scheduler.schedule(colorLetter(wordStartIndex + i), i * durationPerLetter, TimeUnit.MILLISECONDS);
}
}
};
}
//Color the letter on the EDT
private Runnable colorLetter(final int letterIndex) {
return new Runnable() {
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("\t" + (System.currentTimeMillis() - start) + " ms - letter: " + TEXT.charAt(letterIndex));
doc.setCharacterAttributes(letterIndex, 1, textpane.getStyle("Red"), true);
}
});
}
};
}
public void initUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
doc = new DefaultStyledDocument();
textpane = new JTextPane(doc);
textpane.setText(TEXT);
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
panel.add(textpane);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Reminder reminder = new Reminder();
reminder.initUI();
reminder.startColoring();
}
});
}
}

Related

java- creating a clock without using the built in clock class

I am trying to create a program as practice in which the clock ticks every second. I tried to find information on this, but it was either too complicated for what I have learned, or not relevant.
I would like it to sort of work like this:
Clock starts at time: 12:00:00 AM
Clock has been set to time: 11:59:00 PM
TICK: 11:59:01 PM
This is the code that I have written so far:
public class Clock {
public static void main(String[] args) {
SimpleClock clock = new SimpleClock();
System.out.println("Clock starts at time: " + clock.time());
clock.set(11, 59, 00, false);
System.out.println("Clock has been set to time: " + clock.time());
for (int j = 0; j < 60; j++) {
for (int i = 0; i < 60; i++) {
clock.tick();
System.out.println("TICK: " + clock.time());
}
}
System.out.println("Clock finally reads: " + clock.time());
}
}
The GUI:
public class ClockView extends JFrame {
/* -----------------Private Member variables --------------------- */
private static final long serialVersionUID = 1L;
private static int ROWS_IN_GRID = 2;
private static int COLS_IN_GRID = 1;
private static int BUTTON_ROWS = 1;
private static int BUTTON_COLS = 2;
private SimpleClock clock;
private JLabel face;
/**
* Constructor. Takes a SimpleClock as an argument and builds a graphical
* interface using that clock the model. The Tick button increments the
* clock by 1 second, while the Reset button sets the clock back to midnight
* (12:00:00AM). *
*
* #param clock
* - the clock instance used to store the time for the view
*/
public ClockView(SimpleClock clock) {
super("SimpleClock Demo");
this.clock = clock;
this.face = new JLabel("<html><span style='font-size:20px'>"
+ this.clock.time() + "</span></html>");
this.setLayout(new GridLayout(ROWS_IN_GRID, COLS_IN_GRID));
this.add(this.face);
JPanel buttonPanel = new JPanel(
new GridLayout(BUTTON_ROWS, BUTTON_COLS));
JButton tickButton = new JButton("Tick");
tickButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
clock.tick();
ClockView.this.face
.setText("<html><span style='font-size:20px'>"
+ clock.time() + "</span></html>");
}
});
buttonPanel.add(tickButton);
JButton resetButton = new JButton("reset");
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clock.set(12, 0, 0, true);
ClockView.this.face
.setText("<html><span style='font-size:20px'>"
+ clock.time() + "</span></html>");
}
});
buttonPanel.add(resetButton);
this.add(buttonPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ClockView v = new ClockView(new SimpleClock());
}
}
I am quit positive my logical error occurs in public void tick() of class SimpleClock
Essentially, it just switches from am to pm because I currently have the program switching at the end of the while loop. I know I have to move it, but I not sure how to as the clock doesn't even tick in the first place.
Your current tick method contains a lot of loop that will always end up with a time >= 12hours. Why ? Because you will add one seconds until the loop condition isn't meet. So until hours >= 12 but also somethime until minutes = 59 or seconds = 59
You should only add one seconds like the comment said: Advances the clock by 1 second. .
And then do the specific checks.
public void tick(){
seconds++;
if(seconds => 60){
seconds = 0;
minutes++;
if(....)
...
}
}
Also, morning will always be switch here, but you should only do it if hours reach the limit

Measuring time of different sort methods

I am writing code that is supposed to measure different sort times for different sort methods with arrays of a specific size and display the output time in a GUI. I have got it working for the most part but the program is not displaying the same result each time. For instance, it will say 0.2 milliseconds for one run and 0.1 for the next. I believe the problem is in the runSort() method. Could anybody help me? Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
public class Benchmarks extends JFrame
{
private static int numberOfRuns = 20;
private JTextField arraySizeInput, display;
private String sortMethodNames[] =
{"Selection Sort", "Insertion Sort", "Mergesort", "Quicksort", "Arrays.sort"};
private JComboBox chooseSortMethod;
private final long seed;
private int arraySize;
// Constructor
public Benchmarks()
{
super("Benchmarks");
Container c = getContentPane();
c.setLayout(new GridLayout(6, 1));
c.add(new JLabel(" Array size: "));
arraySizeInput = new JTextField(4);
arraySizeInput.setText("1000");
arraySizeInput.selectAll();
c.add(arraySizeInput);
chooseSortMethod = new JComboBox(sortMethodNames);
c.add(chooseSortMethod);
JButton run = new JButton("Run");
run.addActionListener(new RunButtonListener());
c.add(run);
c.add(new JLabel(" Avg Time (milliseconds): "));
display = new JTextField(" Ready");
display.setBackground(Color.YELLOW);
display.setEditable(false);
c.add(display);
// Use the same random number generator seed for all benchmarks
// in one run of this program:
seed = System.currentTimeMillis();
}
// Fills a[] with random numbers and sorts it using the sorting method
// specified in sortMethod:
// 1 -- Selection Sort
// 2 -- Insertion Sort
// 3 -- Mergesort
// 4 -- Quicksort
// This is repeated numberOfRuns times for better accuracy
// Returns the total time it took in milliseconds.
private long runSort(double[] a, int sortMethod, int numberOfRuns)
{
long startTime;
long endTime;
long diffTime;
Random generator = new Random(seed);
for(int i= a.length-1; i>0; i--)
{
a[i]= generator.nextDouble();
}
startTime= System.currentTimeMillis();
switch(sortMethod)
{
case 1: //Selection Sort
SelectionSort sel = new SelectionSort();
sel.sort(a);
break;
case 2: //Insertion Sort
InsertionSort nsert= new InsertionSort();
nsert.sort(a);
break;
case 3: //Merge Sort
Mergesort merge = new Mergesort();
merge.sort(a);
break;
case 4: // Quick Sort
Quicksort quick = new Quicksort();
quick.sort(a);
break;
}
endTime= System.currentTimeMillis();
diffTime= endTime- startTime;
return diffTime ;
}
// Handles Run button events
private class RunButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inputStr = arraySizeInput.getText().trim();
try
{
arraySize = Integer.parseInt(inputStr);
}
catch (NumberFormatException ex)
{
display.setText(" Invalid array size");
arraySize = 0;
return;
}
if (arraySize <= 0)
{
display.setText(" Invalid array size");
return;
}
if (arraySize <= 0)
return;
int sortMethod = chooseSortMethod.getSelectedIndex() + 1;
double a[] = new double[arraySize];
double avgTime = (double)runSort(a, sortMethod, numberOfRuns)
/ numberOfRuns;
display.setText(String.format(" %.2f", avgTime));
arraySizeInput.selectAll();
arraySizeInput.requestFocus();
System.out.println("Array size = " + arraySize +
" Runs = " + numberOfRuns + " " +
sortMethodNames[sortMethod - 1] + " avg time: " + avgTime);
}
}
//************************************************************
public static void main(String[] args)
{
numberOfRuns = 20;
if (args.length > 0)
{
int n = -1;
try
{
n = Integer.parseInt(args[0].trim());
}
catch (NumberFormatException ex)
{
System.out.println("Invalid command-line parameter");
System.exit(1);
}
if (n > 0)
numberOfRuns = n;
}
Benchmarks window = new Benchmarks();
window.setBounds(300, 300, 180, 200);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);
}
}
Thank you for the help.
You are getting different results because of many minor factors, like how busy the computer is at the time. Also, System.currentTimeMillis() is inherently inaccurate; on some systems, 5 ms may be measured as 0 to 10 ms. To get better accuracy when measuring small amounts of time, you should use System.nanoTime(). Also, you should have nothing at all between measuring the start time and measuring the end time. That means no for or while loops, if statements, or switch statements.
What you try is simply not possible. You'll need a system with garanteed cpu time. But scheduling and different loads makes it impossible to get exact times. Additional the Java-Garbage collection and things like optimizing from the java enviroment changes your results. you could use a framework like junitbenchmark and let the code run multible times - but rembemer this will not give you a "really usable" result. It can help you to determ the speed of each algorithm in relation to each other.

Difficulty using threads with Swing

package combatframe;
import javax.swing.*;
import java.awt.event.*;
import static java.lang.Math.PI;
import javax.swing.border.*;
public class CombatFrame extends JFrame
{
String[] Ships = {"Battleship", "Cruiser", "Frigate"};
JComboBox attackCombo = new JComboBox(Ships);
JComboBox targetCombo = new JComboBox(Ships);
JButton calculate = new JButton();
JPanel mainPanel = new JPanel();
JPanel outPanel = new JPanel();
JPanel shipPanel = new JPanel();
JTextArea outText = new JTextArea("Results: ", 11, 30);
JTextArea attackStats = new JTextArea("Attacker stats.", 10,10);
JTextArea targetStats = new JTextArea("Target stats.", 10,10);
public static void main(String[] args)
{
CombatFrame combatFrame = new CombatFrame();
}
public CombatFrame()
{
this.setSize(500,500);
this.setTitle("OTG Combat Simulator");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EventListener c1 = new EventListener();
EventListener c2 = new EventListener();
EventListener calc = new EventListener();
calculate.setText("Calculate!");
Border b1 = BorderFactory.createTitledBorder("Result");
outPanel.setBorder(b1);
Border b2 = BorderFactory.createTitledBorder("Ship Classes");
shipPanel.setBorder(b2);
mainPanel.add(shipPanel);
mainPanel.add(outPanel);
shipPanel.add(attackStats);
shipPanel.add(attackCombo);
shipPanel.add(targetCombo);
shipPanel.add(targetStats);
outPanel.add(calculate);
outPanel.add(outText);
attackCombo.addActionListener(c1);
attackCombo.setSelectedItem("Battleship");
targetCombo.addActionListener(c2);
targetCombo.setSelectedItem("Battleship");
calculate.addActionListener(calc);
this.add(mainPanel);
this.setVisible(true);
}
public double hitProbability(double factor)
{
double hitCount = (double)(Math.random() * 1.001 * factor );
return hitCount;
}
public double Combat(double[] turnArray)
{
double rRange = turnArray[0];
double rAngular = turnArray[1];
double rRadius = turnArray[2];
double damage = turnArray[3];
double appliedDamage = 0;
int[] attHit =
{
0, 0, 0
};
int[] strikes =
{
0, 0, 0, 0, 0
};
double[] damageMod =
{
0,0.4,0.75,1.0,1.25
};
double roll1, roll2, roll3;
roll1 = hitProbability(rRadius);
roll2 = hitProbability(rAngular);
roll3 = hitProbability(rRange);
if (roll1 <=1)
attHit[0]++;
if (roll2 <=1)
attHit[1]++;
if (roll3 <=1)
attHit[2]++;
switch (attHit[0]+attHit[1]+attHit[2])
{
case 3:
double wrecker = Math.random();
if (wrecker >= 0.95 - Math.random())
strikes[4]++;
else
strikes[3]++;
break;
case 2:
strikes[2]++;
break;
case 1:
strikes[1]++;
break;
case 0:
strikes[0]++;
break;
}
for (int x=0; x<5; x++)
{
appliedDamage += strikes[x]*Damage*
(Math.random()+Math.random())*damageMod[x];
}
return appliedDamage;
}
private class EventListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource()== attackCombo)
{
switch ((String)attackCombo.getSelectedItem())
{
case "Battleship":
Attacker attackBS = new Attacker(50000.0, 400.0, 0.01, 45000.0, 400.0,
300.0, 10.0, 10000.0, 250.0);
break;
case "Cruiser":
Attacker attackCr = new Attacker(25000.0, 125.0, 0.23, 22500.0, 150.0,
600.0, 5.0, 5000.0, 75.0);
break;
case "Frigate":
Attacker attackFr = new Attacker(2500.0, 40.0, 0.365, 1000.0, 39.0,
900.0, 2.0, 1200.0, 25.0);
break;
}
attackStats.setText("Optimal: " + Attacker.Optimal
+ "\n Weapon Sig: " +Attacker.Attack_Signature
+ "\n Tracking: " + Attacker.Tracking
+ "\n Range: " + Attacker.Range
+ "\n Ship Sig: " + Attacker.Target_Signature
+ "\n Velocity: " + Attacker.Orbital
+ "\n Cycle Time" + Attacker.Period
+ "\n Health: " + Attacker.Health
+ "\n Damage: " + Attacker.Damage);
}
if (e.getSource()==targetCombo)
{
switch ((String)targetCombo.getSelectedItem())
{
case "Battleship":
Target targetBS = new Target(50000.0, 400.0, 0.01, 45000.0, 400.0,
300.0, 10.0, 10000.0, 250.0);
break;
case "Cruiser":
Target targetCr = new Target(25000.0, 125.0, 0.23, 22500.0, 150.0,
600.0, 5.0, 5000.0, 75.0);
break;
case "Frigate":
Target targetFr = new Target(2500.0, 40.0, 0.365, 1000.0, 39.0,
900.0, 2.0, 1200.0, 25.0);
break;
}
targetStats.setText("Optimal: " + Target.Optimal
+ "\n Weapon Sig: " + Target.Attack_Signature
+ "\n Tracking: " + Target.Tracking
+ "\n Range: " + Target.Range
+ "\n Ship Sig: " + Target.Target_Signature
+ "\n Velocity: " + Target.Orbital
+ "\n Cycle Time" + Target.Period
+ "\n Health: " + Target.Health
+ "\n Damage: " + Target.Damage);
}
if (e.getSource()==calculate)
{
double[] attackArray =
{//RRange,RAngular,RRadius,Attacker.Damage
0,0,0,0
};
double[] targetArray =
{//RRange,RAngular,RRadius,Target.Damage
0,0,0,0
};
double attackDamage = 0, targetDamage = 0;
for (int i=1; i<1000; i++)
{
if ((i+1)%Attacker.Period==0)
{
double rRange = Attacker.Optimal/Target.Range;
double rAngular =
((Math.sin(PI/4)*(Target.Orbital/Target.Range))
/Attacker.Tracking);
double rRadius = Attacker.Attack_Signature/
Target.Target_Signature;
attackArray[0] = rRange;
attackArray[1] = rAngular;
attackArray[2] = rRadius;
attackArray[3] = Attacker.Damage;
attackDamage += Combat(attackArray);
if (attackDamage >= Target.Health)
{
outText.setText("Attacker wins!");
break;
}
}
if (i%Target.Period==0)
{
double rRange = Target.Optimal/Attacker.Range;
double rAngular =
((Math.sin(PI/4)*(Attacker.Orbital/Attacker.Range))
/Target.Tracking);
double rRadius = Target.Attack_Signature/
Attacker.Target_Signature;
targetArray[0] = rRange;
targetArray[1] = rAngular;
targetArray[2] = rRadius;
targetArray[3] = Target.Damage;
targetDamage += Combat(targetArray);
if (targetDamage >= Attacker.Health)
{
outText.setText("Target wins!");
break;
}
}
}
}
}
}
}
I'm attempting to build a very simple combat simulation frame. It builds 2 combo-boxes and assigns stats based upon the selections therein.
User then hits the calculate button, and out pops the result into the Results field. That all works fine.
I'd like the GUI to append each 'turn' of combat into the Results textfield outText - and I think I could do that easily enough. I'd like it to do so with a slight delay on any turn there is combat - I'd use a Thread.sleep(10) in each if-statement to do with an active turn for each ship.
The only problem with all that is I can't work out how to hold the GUI on one thread - which updates when prompted by the combat calculations after the button is clicked - and the thread handling all the calculations with delays.
I know if I try and run both on the same thread, the GUI will simply freeze up, do all the calculations with applicable delays, then throw out the entire appended lump at once into the results field.
Can anyone offer me any pointers, advice or cyanide? Anything, anything to make the pain go away...
Suspect that SwingWorker would be a good idea, but still can't work out how to actually implement that within my code.
Clarification: My biggest concern is that I can't work out how to implement SwingWorker, or some similar multi-thread process, in order to run the GUI and background calculations in parallel.
I will just take a stab at this since I think I understand what you are trying to do. Maybe what you are looking for is to create a new runnable each time the button is clicked:
class Turn implements Runnable {
private final Object source;
private final String attackComboMove;
private final String targetComboMove;
public Turn(Object src, String acm, String tcm) {
source = src;
attackComboMove = acm;
targetComboMove = tcm;
}
#Override public void run() {
// may want to disable GUI buttons here
if (source == attackCombo) {
switch (attackComboMove) {
// ...
// ...
// ...
}
append("attack combo results");
} else if (source == targetCombo) {
switch (targetComboMove) {
// ...
// ...
// ...
}
append("target combo results");
} else if (source == calculate) {
// ...
for (int i = 1; i < 1000; i++) {
// ...
attackDamage += combat(attackArray);
append("combat results: " + attackDamage + " total damage");
if (attackDamage >= target.health) {
append("Attacker wins!");
break;
}
}
}
// and enable the buttons again when combat is over
}
private void append(String text) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
outTextArea.append("\n" + text);
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
It sounds like you just want a scrolling list of the attacks as they happen and that's what this will do for you. IMO it is the right way to do it and ultimately the simplest.
When the user clicks the button you do:
new Thread(new Turn(e.getSource(), (String)attackCombo.getSelectedItem(), (String)targetCombo.getSelectedItem())).start();
(Or make a variable for the new thread if you need to be able to end it early for some reason or alter parameters.)
This pattern can easily be adapted to SwingWorker if it is long-running, just extend SwingWorker and do the same thing but override doInBackground() instead of run().
Otherwise if you are intending to make a real-time simulation and need a background thread you will need to make run/doInBackground be a while(running) loop and use flags and/or some kind of wait/notify scheme when you need to change parameters or calculate a turn.
You could use javax.swing.Timer to schedule something to happen N milliseconds in the future. Note that 10 in Java time usually means 10 milliseconds, which is a nearly imperceptible amount of time. If you want to sleep or delay for a second, use 1000 milliseconds, 10 seconds = 10000 milliseconds, etc. Example:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class GameFrame extends JFrame
{
private JPanel _contentPane;
private GameFrame _mainFrame;
private JButton _jButton;
private JTextArea _jTextArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
GameFrame frame = new GameFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(640/2, 480/2);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public GameFrame()
{
_mainFrame = this;
_contentPane = new JPanel();
_mainFrame.setContentPane(_contentPane);
_contentPane.setLayout(new BorderLayout());
_jTextArea = new JTextArea();
_contentPane.add(_jTextArea, BorderLayout.CENTER);
_jButton = new JButton("Go");
_jButton.addActionListener(new GoButtonListener());
_contentPane.add(_jButton, BorderLayout.SOUTH);
}
class GoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
_jTextArea.append("Please wait...\n");
Timer timer = new Timer(10000, new LaterListener());
timer.start();
}
}
class LaterListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
_jTextArea.append("Ten seconds later!\n");
}
}
}

JAVA time it takes between button clicks

I have some code which displays a GUI of two buttons and the goal is to press one button twice to display the time it took in milliseconds between the button clicks.
Although my issue is that the time is always 0. Any suggestions?
I also want to implement a way to get the time between the clicks of button a and button b.
Any tips?
Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonViewer
{
static int countA = 0;
static int countB = 0;
public static void main( String[] args )
{
JFrame frame = new JFrame();
GridLayout layout = new GridLayout(2,2);
frame.setLayout(layout);
JButton buttonA = new JButton("Button A");
frame.add(buttonA);
class ClickListenerOne implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
countA++;
long StartA = System.currentTimeMillis();
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis();
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");
}
}
}
JButton buttonB = new JButton("Button B");
frame.add(buttonB);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
countB++;
long StartB = System.currentTimeMillis();
if (countB % 2 == 0)
{
long EndB = System.currentTimeMillis();
long differenceB = (EndB - StartB);
System.out.println(differenceB + " Elapsed");
}
}
}
ActionListener mButtonAClicked = new ClickListenerOne();
buttonA.addActionListener(mButtonAClicked);
ActionListener mButtonBClicked = new ClickListenerTwo();
buttonB.addActionListener(mButtonBClicked);
frame.setSize( 200, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible(true);
}
}
Set the StartA in the button's first click, i.e.
long StartA;
public void actionPerformed( ActionEvent event )
{
countA++;
if (countA % 2 != 0)
StartA = System.currentTimeMillis();
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis();
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");
}
This will give you the difference between first click and second click
In your code:
class ClickListenerOne implements ActionListener {
// int startA; ?
public void actionPerformed( ActionEvent event )
{
countA++;
long StartA = System.currentTimeMillis(); // you are reading time
//after mouse click event
if (countA % 2 == 0)
{
long EndA = System.currentTimeMillis(); // variable name should not be
//declared with capital letter
long differenceA = (EndA - StartA);
System.out.println(differenceA + " Elapsed");// then you are computing
//elapsed time in the same click event
// startA = endA; // updated the time after each event?
}
}}
This way you won't have elapsed time between subsequent mouse click event. The idea is to declare startTime as a member in your class deceleration. Compute the elapsed time as you are doing and then update the startTime by setting it to the endTime.
use System.nanotime() instead of System.currentTimeMillis()
public void actionPerformed( ActionEvent event )
{
countA++;
if(countA % 2 != 0){
StartA = System.nanoTime();
}
if (countA % 2 == 0)
{
EndA = System.nanoTime();
differenceA = EndA- StartA;
System.out.println(differenceA);
}
}

Title updates differently than Graphics

I've been working on a simple program to input a list of times and show how many hours, minutes, and seconds are left until then. I'm having a delay issue where the JFrame is not being update at the same time as the title.
picture: http://i.imgur.com/se08bXm.png
Here is my source code:
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Schedule extends JFrame {
public String out = "";
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
new Schedule();
}
public Schedule() throws FileNotFoundException, InterruptedException {
setSize(300, 60);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calendar now = new GregorianCalendar();
Scanner in = new Scanner(new File("schedule"));
ArrayList<Calendar> list = new ArrayList<Calendar>();
ArrayList<String> list2 = new ArrayList<String>();
while(in.hasNextInt()) {
Calendar then = new GregorianCalendar();
then.set(Calendar.HOUR_OF_DAY, in.nextInt());
then.set(Calendar.MINUTE, in.nextInt());
then.set(Calendar.SECOND, in.nextInt());
list.add(then);
list2.add(in.nextLine());
}
while(true) {
now = new GregorianCalendar();
int i = 0;
for (Calendar c : list) {
if (c.compareTo(now) > 0) {
out = (difference(now, c) + list2.get(i));
setTitle(out);
long t = System.currentTimeMillis();
while (System.currentTimeMillis() - t < 1000);
repaint();
break;
}
i++;
}
}
}
private String difference(Calendar now, Calendar then) {
String out = "";
int seconds = (int) ((then.getTimeInMillis() - now.getTimeInMillis()) / 1000);
int minutes = seconds / 60;
seconds %= 60;
int hours = minutes / 60;
minutes %= 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
#Override
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(0, 0, 300, 60);
g.setColor(Color.YELLOW);
g.setFont(new Font("", 0, 32));
g.drawString(out, 5, 50);
}
}
How can I fix my code so that the JFrame updates at the same time as the title?
I've tried removing the
while (System.currentTimeMillis() - t < 1);
so that it updates constantly, but that just makes the text flash very fast.
Any ideas? thanks.

Categories

Resources