|
|
Re: Help Needed
|
Posted: Nov 15, 2006 7:24 AM
|
|
First I separated Thread and Frame, because in my Opinion sending the Thread to sleep also causes that the frame is not painted. Don't know if this is right or wrong, because It didn't work anyway.
So I came up with the idea not to paint directly into the frame, but into a panel displayed into the frame and that worked. Here's my code:
/*
* Clock.java
*
* Created on 13. November 2006, 12:02
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package keylogger;
/**
*
* @author Neumi
*/
import java.util.*;
import java.text.DateFormat;
import java.awt.*;
import java.awt.geom.*;
public class Clock extends Frame{
public Clock() {
setBounds(300,200,200,200);
setLayout(new java.awt.BorderLayout());
myPanel = new ClockPanel();
add(myPanel, java.awt.BorderLayout.CENTER);
setVisible(true);
new ClockSetter(this).start();
}
public void displayTime() {
myPanel.repaint();
}
public static void main(String str[]) {
Clock myclock = new Clock();
}
private ClockPanel myPanel;
private static class ClockSetter extends Thread {
private Clock clockFrame;
boolean doRunThread = true;
public ClockSetter (Clock clockFrame) {
this.clockFrame = clockFrame;
}
public void run() {
doRunThread = true;
while (doRunThread) {
clockFrame.displayTime();
try {
sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
System.out.println(e.getMessage());
}
}
}
public void stopThread() {
doRunThread = false;
notify();
}
}
private class ClockPanel extends java.awt.Panel {
public ClockPanel() {
super();
}
public void paint(Graphics g) {
super.paint(g);
// get the time and convert it to a date
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
// format it and display it
DateFormat dateFormatter = DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(date), 5, 10);
}
}
}
|
|