Painting Clock, Overlaps the current String display
Code :
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Calendar;
import javax.swing.*;
public class MyClock extends JPanel implements Runnable {
Thread runner;
public MyClock() {
setDoubleBuffered(true);
setFocusable(true);
setLayout(null);
}
public void paintComponent(Graphics g) {
Calendar now = Calendar.getInstance();
int hrs = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
String time = zero(hrs) + ":" + zero(min) + ":" + zero(sec);
g.drawString(time, 60, 40);
repaint();
}
public String zero(int num) {
String number = (num < 10) ? ("0" + num) : ("" + num);
return number;
}
public void start() {
if (runner == null) {
runner = new Thread(this);
}
runner.start();
}
public void run() {
while (runner == Thread.currentThread()) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
System.out.println("Thread failed");
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 300);
f.add(new MyClock());
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
i just gode this code from the web, with a little bit of modification, i need to implement a digital clock for another project.. i just cant figure out why does the next painting overlaps the current one.. any help please.
Re: Painting Clock, Overlaps the current String display
by the way.. my goal is.. to create a separate class as a Clock, but extends as a JPanel not a JFrame, i just want to add/call it to any JFrame window i have or in any JPanel/Container
Re: Painting Clock, Overlaps the current String display
1- Don't just throw code together you get from the internet. Take the time to really understand what's going on. You'll save yourself a ton of headaches. Recommended reading: Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)
2- Don't call repaint() from a paint method, including paintComponent(). Use a Swing Timer instead, otherwise you're going to be constantly drawing, which is really going to eat up a lot of resources.
3- Your zero() method is doing the job of a DecimalFormat instance.
4- JPanel's paintComponent() method redraws the background, which in effect clears out any previously drawn frames. Start your paintComponent() method with a call to super.paintComponent() in order to maintain that functionality.