Affichage des articles dont le libellé est java timer. Afficher tous les articles
Affichage des articles dont le libellé est java timer. Afficher tous les articles

Java - How To Create a CountDown Timer In Java Netbeans

How to Create a CountDown Timer App In Java Netbeans

How To Create a CountDown Timer In Java Netbeans


In this Java Tutorial we will see How To Make a CountDown Timer With Minutes and Seconds Numbers In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What This Project Do:

This app lets users set a countdown in minutes and seconds, then start the timer.
The timer counts down and updates the display every second, showing the remaining time from the specified initial time.
After reaching zero on the countdown, the timer stops, and a 'Time's Up!' message is shown.





Project Source Code:



package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;


public class CountDownTimer {

    private int minutes = 0;
    private int seconds = 0;
    
    private Timer timer;
    private JLabel timerLabel;
    private JButton startButton;
    private JTextField minutesField, secondsField;
    
    public CountDownTimer(){
        
        // Create the main JFrame
        JFrame frame = new JFrame("Count Down Timer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 250);
        frame.getContentPane().setBackground(Color.white);
        frame.setLocationRelativeTo(null);
        
        // Create the content panel with BorderLayout
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BorderLayout());
        
        // Create and configure the timer label
        timerLabel = new JLabel("Time remaining: 00:00");
        timerLabel.setHorizontalAlignment(SwingConstants.CENTER);
        timerLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
        timerLabel.setForeground(Color.DARK_GRAY);
        
        // Create the input panel for timer values
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        inputPanel.setBackground(Color.white);
        
        // Create input fields and start button
        minutesField = new JTextField(2);
        secondsField = new JTextField(2);
        startButton = new JButton("Start Timer");
        startButton.setBackground(new Color(30, 144, 255));
        startButton.setForeground(Color.white);
        startButton.setFocusPainted(false);
        startButton.setBorderPainted(false);
        
        // Add action listener for the start button
        startButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
            
               startTimer();
            
            }
        });
        
        // Add components to input panel
        inputPanel.add(new JLabel("Minutes:"));
        inputPanel.add(minutesField);
        inputPanel.add(new JLabel("Seconds:"));
        inputPanel.add(secondsField);
        inputPanel.add(startButton);
        
        // Add components to content panel
        contentPanel.add(timerLabel, BorderLayout.CENTER);
        contentPanel.add(inputPanel, BorderLayout.SOUTH);
        
        // Add content panel to the main JFrame
        frame.add(contentPanel);
        frame.setVisible(true);
                
    }
    
    private void startTimer(){
        // Stop the existing timer if it's running
        if(timer != null && timer.isRunning())
        {
            timer.stop();
        }
        
        try
        {
            // Parse input values for minutes and seconds
          minutes = Integer.parseInt(minutesField.getText());
          seconds = Integer.parseInt(secondsField.getText());
        }
        catch(NumberFormatException ex)
        {
            JOptionPane.showMessageDialog(null, "Invalid input. Please enter valid minutes and seconds.");
            return;
        }
        
        int totalSeconds = minutes * 60 + seconds + 1;
        
        
        // Create a new timer with an ActionListener
        timer = new Timer(1000, new ActionListener() {
            int count = totalSeconds;
            @Override
            public void actionPerformed(ActionEvent e) {
                
                count--;
                
                if(count >= 0)
                {
                  int remainningMinutes = count/60;
                  int remainningSeconds = count%60;
                  timerLabel.setText(String.format("Time Remaining: %02d:%02d", remainningMinutes, remainningSeconds));
                }
                else
                {
                  timer.stop();
                  timerLabel.setText("Time's Up!");
                }
                
            }
        });
        
        timer.start();  // Start the timer
        
    }
    
    
    public static void main(String[] args){
        
        SwingUtilities.invokeLater(()-> new CountDownTimer());
        
    }
    
    
}


The Final Result:



CountDown Timer In Java Netbeans

Java CountDown Timer In Netbeans




Java - Create Stopwatch App

How to Create a Chronometer App in Java NetBeans

How to Create a Chronometer App in Java NetBeans


In this Java Tutorial we will see How To Make a graphical user interface for a chronometer application In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create a window that display time in the format "HH:mm:ss.SSS" (hours, minutes, seconds, and milliseconds).
When the "Start" button is clicked, the chronometer starts measuring time.
Conversely, when the "Stop" button is clicked, the chronometer stops measuring time.





Project Source Code:




package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Dictionary;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;


public class ChronometerApp extends JFrame {

    private JLabel timeLabel;
    private JButton startButton;
    private JButton stopButton;
    private Timer timer;
    private long startTimer;
    private boolean isRunning;
    
    public ChronometerApp(){
        setTitle("Chronometer App");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setResizable(false);
        initialize(); // initialize the user interface
        setVisible(true);
    }
    
    private void initialize(){
        
        // Create and configure the time display label
        timeLabel = new JLabel("00:00:00.000");
        timeLabel.setFont(new Font("Arial", Font.BOLD, 48));
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        
        // Create and configure the Start button
        startButton = new JButton("Start");
        startButton.setFont(new Font("Arial", Font.PLAIN, 16));
        startButton.setBackground(new Color(63, 81, 181));
        startButton.setForeground(Color.white);
        startButton.setFocusPainted(false);
        startButton.setBorderPainted(false);
        
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
               start(); // Start the chronometer
            
            }
        });
        
        // Create and configure the Stop button
        stopButton = new JButton("Stop");
        stopButton.setFont(new Font("Arial", Font.PLAIN, 16));
        stopButton.setBackground(new Color(244, 67, 54));
        stopButton.setForeground(Color.white);
        stopButton.setEnabled(false);
        stopButton.setFocusPainted(false);
        stopButton.setBorderPainted(false);
        
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
               stop(); // Stop the chronometer
            
            }
        });
        
        // Create a panel for the buttons and arrange them horizontally
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.white);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,0,10,0));
        buttonPanel.add(startButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(20, 0)));
        buttonPanel.add(stopButton);
        
        // Set up the layout and add components to the content pane
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(timeLabel, BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        
        // Create a timer to update the chronometer display every 10 milliseconds
        timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                updateTimer(); // Update the chronometer display
            
            }
        });
        
    }
    
    private void start(){
    
        if(!isRunning){
            startTimer = System.currentTimeMillis();
            timer.start(); // start the timer
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            isRunning = true;
        }
        
    }
    
    private void stop(){
    
        if(isRunning){
            timer.stop(); // stop the timer
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            isRunning = false;
        }
        
    }
    
    private void updateTimer(){
    
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - startTimer;
        
        // Calculate hours, minutes, seconds, and milliseconds
        long hours = elapsedTime / 3600000;
        long minutes = (elapsedTime % 3600000) / 60000;
        long seconds = (elapsedTime % 60000) / 1000;
        long milliseconds = elapsedTime % 1000;
        
        // Format the time components as strings with leading zeros if needed
        DecimalFormat format = new DecimalFormat("00");
        String timeString = format.format(hours)+":"
                            +format.format(minutes)+":"
                            +format.format(seconds)+"."
                            +format.format(milliseconds);
        
        // Update the time label with the formatted time
        timeLabel.setText(timeString);
        
    }
    
    
    public static void main(String[] args){
        
        SwingUtilities.invokeLater(() -> {
        
            new ChronometerApp();
        
        });
        
        
    }
    
    
}


The Final Result:



Java Stopwatch Project Tutorial

Chronometer App in Java NetBeans






Java Digital Clock In Netbeans

How to Create Digital Clock in Java NetBeans

Java Digital Clock In Netbeans




In this Java Tutorial we will see How To Make a Digital Clock, With Hours, Minutes and Seconds In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create a JPanel named centerPanel with a visually appealing gradient background.
- Create a JLabel to display the current time.
Update Timer continuously using a Timer that calls the updateClock method every second.





Project Source Code:


package new_tutorials;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;



public class Digital_Clock extends JFrame {

    private JLabel timeLabel;
    
    public Digital_Clock(){
    
        setTitle("Digital Clock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setResizable(false);

        
    // Create a JPanel with a background gradient    
    JPanel centerPanel = new JPanel(new GridBagLayout()){
    
        @Override
        protected void paintComponent(Graphics g){
            
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            
            // Define a gradient paint for the background
            GradientPaint gradient = new GradientPaint(new Point(0,0), new Color(37, 116, 169),
                                new Point(0,getHeight()), new Color(78, 154, 217) );
            
            g2d.setPaint(gradient);
            
            // Fill the panel with the gradient paint
            g2d.fillRect(0,0,getWidth(), getHeight());
            g2d.dispose();          
        }
    };
    add(centerPanel);
    
    timeLabel = new JLabel();
    timeLabel.setFont(new Font("Arial", Font.BOLD, 56));
    timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
    timeLabel.setForeground(Color.white);
    
    
     // Add timeLabel to the center panel with padding
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(30, 30, 30, 30);  // Padding
        
        centerPanel.add(timeLabel, gbc);
        
        // Start a timer to update the clock every second
        Timer timer = new Timer(1000, e->updateClock());
        timer.start();
        
        // Initial clock update
        updateClock();
    
    }
    
    private void updateClock(){
        
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String currentTime = sdf .format(new Date());
        timeLabel.setText(currentTime);
        
    }
    
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(()->{});
        
           Digital_Clock dc = new Digital_Clock();
           dc.setVisible(true);
        
    }
    
    
}


The Final Result:



Java Digital Clock