You are viewing our Forum Archives. To view or take place in current topics click here.
A basic Java clock.
Posted:

A basic Java clock.Posted:

Vysmo
  • New Member
Status: Offline
Joined: May 17, 201113Year Member
Posts: 6
Reputation Power: 0
Status: Offline
Joined: May 17, 201113Year Member
Posts: 6
Reputation Power: 0
This is a basic Java Digital clock I made and appended using a few tutorials and docs.oracle.com. It's a simple design using a JTextField inside a JPanel to display the time in the form 00:00:00. I just figured I'd share the code with you so you can try it out for yourselves and let me know what you think.


import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import javax.swing.*;

@SuppressWarnings("serial") //Ignore unless you're using Eclipse IDE
public class Clock extends JFrame {
   public static void main(String[] args) {
      new Clock();
   }
   @SuppressWarnings("unused") //Ignore as above.
   private static long serialVersionUID = 1L;
   
   JTextField timeF;
   JPanel panel;
   
   public Clock() {
      super("Java Clock");
      setSize(225,200);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      setResizable(false);
      setLocationRelativeTo(null);
      
      panel = new JPanel();
      panel.setLayout(new FlowLayout());
      
      timeF = new JTextField(10);
      timeF.setEditable(false);
      timeF.setFont(new Font("Arial", Font.PLAIN, 48));
      timeF.setHorizontalAlignment(SwingConstants.CENTER);
      
      panel.add(timeF);
      
      add(panel);
      
      Timer t = new Timer(1000,new Listener());
      t.start();
   }
   
   class Listener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         Calendar newCal = Calendar.getInstance();
         
         int hour = newCal.get(Calendar.HOUR_OF_DAY);
         int min = newCal.get(Calendar.MINUTE);
         int sec = newCal.get(Calendar.SECOND);
         
         if(min < 10 && sec < 10) {
            timeF.setText(hour+":"+"0"+min+":"+"0"+sec);
         } else if(min < 10 && sec > 10) {
            timeF.setText(hour+":"+"0"+min+":"+sec);
         } else if(min > 10 && sec < 10){
            timeF.setText(hour+":"+min+":"+"0"+sec);
         } else {
            timeF.setText(hour+":"+min+":"+sec);
         }
      }
   }
}


It's really crappy if you ask me but I've just gotten back into Java programming so give me a break
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.