Cari Blog Ini

Jumat, 11 November 2022

Aplikasi Timer dengan Java Visual

 



Berikut Coding untuk APlikasi Timer dengan Java Visual

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

class Aplikasi_Timer2 extends JFrame implements ActionListener
{
int jam=0;
int menit=0;
int detik=0;
int delay=50; //untuk kecepatan waktu

Timer timer=null;

JLabel judul = new JLabel ("Aplikasi Timer");
JLabel label=new JLabel("00:00:00");
JButton btnStart = new JButton("START");
JButton btnStop = new JButton("STOP");

Aplikasi_Timer2 ()
{
    super("Aplikasi Timer");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocation(100,100);
    setSize(300,200);
    }

void KomponenVisual()
    {
     getContentPane().setLayout(null);
     getContentPane().setBackground(Color.magenta);
     
     getContentPane().add(judul);
     judul.setBounds(100,10,100,30);
     judul.setFont(new Font("arial",Font.BOLD,14));

     getContentPane().add(label);
     label.setBounds(90,40,200,30);
     label.setFont(new Font("arial",Font.BOLD,30));
 
     getContentPane().add(btnStart);
     btnStart.setBounds(30,100,100,40);
     btnStart.addActionListener(this);

     getContentPane().add(btnStop);
     btnStop.setBounds(150,100,100,40);
     btnStop.addActionListener(this);

    setVisible(true);
    timer=new Timer(delay, display);
  }
     
 //untuk aksi tombol start dan stop
  public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==btnStart)
{
      if (!timer.isRunning())
      {
       timer.start();
       btnStart.setEnabled(false);
       btnStop.setEnabled(true);
      }
}
if (ae.getSource()==btnStop)
{
    if (timer.isRunning())
      {
        timer.stop();
        btnStart.setEnabled(true);
        btnStop.setEnabled(false);
      } 
}   }

   //untuk perubahan jam
  private ActionListener display=new ActionListener()
{
    public void actionPerformed(ActionEvent e)
{
      String str1=Integer.toString(jam);
      String str2=Integer.toString(menit);
      String str3=Integer.toString(detik);

      if (jam<10) str1="0"+str1;
      if (menit<10) str2="0"+str2;
      if (detik<10) str3="0"+str3;

      label.setText(str1+":"+str2+":"+str3);
      detik++;
      if (detik==60)
{
        detik=0;
        menit++;
        if (menit==60)
{
          menit=0;
          jam++;
          if (jam==24)
            jam=0;
 }  
}    
}   };
        
  public static void main(String args[])
{
Aplikasi_Timer2 at = new Aplikasi_Timer2();
at.KomponenVisual();
  } }