java - Can't figure out how to get my attempt to make a digital clock to keep time -
so assignment (surprise, homework!) make gui represents digital clock 2 lines. first line clock (hh:mm aa), , second line gives date scrolling text (eeee - mmmm dd, yyyy). i've managed of show up, can't figure out how date update computer's clock - meaning run @ 1:47 pm, , never changes 1:48 pm. i've been reading around bit, , seems answer problem use thread , have try{thread.sleep(1000)}
or along lines, after few hours of experimentation, can't figure out how apply have:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.date; import java.text.dateformat; import java.text.simpledateformat; public class innerclasses extends jframe { public innerclasses() { this.setlayout(new gridlayout(2, 1)); add(new timemessagepanel()); add(new datemessagepanel()); } /** main method */ public static void main(string[] args) { test frame = new test(); frame.settitle("clock"); frame.setlocationrelativeto(null); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(280, 100); frame.setvisible(true); } static class timemessagepanel extends jpanel { dateformat timeformat = new simpledateformat("hh:mm aa"); date time = new date(); private string timeoutput = timeformat.format(time); private int xcoordinate = 105; private int ycoordinate = 20; private timer timer = new timer(1000, new timerlistener()); @override protected void paintcomponent(graphics g) { super.paintcomponent(g); g.drawstring(timeoutput, xcoordinate, ycoordinate); } class timerlistener implements actionlistener { @override public void actionperformed(actionevent e) { repaint(); } } } static class datemessagepanel extends jpanel { dateformat dateformat = new simpledateformat("eeee - mmmm dd, yyyy"); date date = new date(); private string dateoutput = dateformat.format(date); private int xcoordinate = 0; private int ycoordinate = 20; private timer timer = new timer(250, new timerlistener()); public datemessagepanel() { timer.start(); } @override protected void paintcomponent(graphics g) { super.paintcomponent(g); if (xcoordinate > getwidth() - 50) { xcoordinate = -50; } xcoordinate += 5; g.drawstring(dateoutput, xcoordinate, ycoordinate); } class timerlistener implements actionlistener { @override public void actionperformed(actionevent e) { repaint(); } } } }
any insight appreciated!
1) move computing logic (what computing logic: new date instance, format it, etc, isnt computing logic: add panel layout, set jframe visible, etc.) recompute()
method
2) call
recompute(); repaint();
in timerlistener
Comments
Post a Comment