Header Ads Widget

Responsive Advertisement

Alarm set program



 

Here’s an enhanced version of an alarm set program in Java that features:

  1. Swing-based GUI (AlarmCountDownWindow) for a countdown timer.
  2. Audio playback using AudioClip for playing an alarm sound when the countdown ends.

Java Alarm Program with AudioClip and GUI

This version uses AudioClip for simpler sound playback, while also creating a countdown interface using the Swing library.

Java

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.applet.AudioClip;

import java.net.URL;

import java.util.Timer;

import java.util.TimerTask;

 

public class AlarmCountDownWindow {

 

    private static JLabel countdownLabel;

    private static int remainingTimeInSeconds;

    private static AudioClip alarmSound;

 

    public static void main(String[] args) {

        // Load the alarm sound

        loadAlarmSound();

 

        // Create and set up the window

        JFrame frame = new JFrame("Alarm Countdown");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(300, 150);

       

        // Panel for holding countdown and button

        JPanel panel = new JPanel();

        frame.add(panel);

        placeComponents(panel);

       

        // Show the window

        frame.setVisible(true);

    }

 

    // Method to load the alarm sound using AudioClip

    private static void loadAlarmSound() {

        try {

            // URL to the alarm sound file (alarm_sound.wav)

            URL soundURL = AlarmCountDownWindow.class.getResource("alarm_sound.wav");

            alarmSound = java.applet.Applet.newAudioClip(soundURL);

        } catch (Exception e) {

            System.out.println("Error loading sound: " + e.getMessage());

        }

    }

 

    // Method to place components in the panel

    private static void placeComponents(JPanel panel) {

        panel.setLayout(null);

       

        // Label to show countdown

        countdownLabel = new JLabel("Enter time (in seconds):", SwingConstants.CENTER);

        countdownLabel.setBounds(50, 20, 200, 25);

        panel.add(countdownLabel);

 

        // TextField to input time

        JTextField timeInput = new JTextField(5);

        timeInput.setBounds(100, 50, 100, 25);

        panel.add(timeInput);

       

        // Start button to set the alarm

        JButton startButton = new JButton("Start");

        startButton.setBounds(100, 80, 100, 25);

        panel.add(startButton);

 

        // ActionListener for start button

        startButton.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                try {

                    remainingTimeInSeconds = Integer.parseInt(timeInput.getText());

                    countdownLabel.setText("Remaining: " + remainingTimeInSeconds + " seconds");

                    startCountdown();

                } catch (NumberFormatException ex) {

                    countdownLabel.setText("Please enter a valid number!");

                }

            }

        });

    }

 

    // Method to start the countdown and alarm

    private static void startCountdown() {

        Timer timer = new Timer();

        TimerTask countdownTask = new TimerTask() {

            @Override

            public void run() {

                if (remainingTimeInSeconds > 0) {

                    remainingTimeInSeconds--;

                    countdownLabel.setText("Remaining: " + remainingTimeInSeconds + " seconds");

                } else {

                    countdownLabel.setText("Time's up! ALARM!");

                    playSound();  // Play sound when the alarm triggers

                    timer.cancel();  // Stop the countdown

                }

            }

        };

        // Schedule task every 1 second

        timer.scheduleAtFixedRate(countdownTask, 1000, 1000);

    }

 

    // Method to play the alarm sound using AudioClip

    private static void playSound() {

        if (alarmSound != null) {

            alarmSound.play();  // Play the alarm sound

        } else {

            System.out.println("Sound not available");

        }

    }

}

 

How to Use:

  1. Sound File:

ü  Place an alarm_sound.wav file in the same directory as your Java class or within the resources folder in your project.

ü  The sound file should be a .wav file, which will be played using AudioClip.

  1. Swing GUI:

ü  Input field: Enter the number of seconds to count down.

ü  Start button: Start the countdown when clicked.

  1. Alarm Sound:

ü  When the countdown reaches zero, an alarm sound will play using the AudioClip.

Key Components:

  1. AudioClip: A simple interface for playing audio clips in Java. It works best with .wav files.

ü  The method play() is used to play the sound.

  1. Swing GUI:

ü  JLabel for displaying the countdown.

ü  JTextField for user input to set the countdown time.

ü  JButton to start the countdown.

  1. Countdown Logic:

ü  The Timer and TimerTask are used to manage the countdown, updating the label every second.

  1. Sound Setup:

ü  loadAlarmSound() is responsible for loading the sound file from resources, and playSound() triggers the alarm sound when the countdown finishes.

Example Setup for Sound:

Ø  Ensure the alarm_sound.wav file is either placed in the same directory as the .class files or in the resource folder.

Ø  The URL points to the location of the sound file, and AudioClip plays the sound.

How It Works:

  1. Input a countdown time (in seconds) into the JTextField.
  2. Click Start to begin the countdown.
  3. The label updates every second to show the remaining time.
  4. When the countdown reaches zero, the sound plays and the label displays “Time’s up! ALARM!”.

This simple program can be enhanced with further features like choosing custom alarm tones or stopping the alarm after it starts playing.

 


Another one approach 
Code 1:
?
package com.kartik.alarm.src.main;

import com.kartik.alarm.src.gui.MainWindow;



public class Driver {

/**
* @param args
*/
public static void main(String[] args) {
MainWindow window = new MainWindow();
window.setVisible(true);
}

}


Code 2:
?
package com.kartik.alarm.src.classes;


import java.util.Timer;
import java.util.TimerTask;

public class Alarm {
private String name;
//Time in seconds.
private long time;
private SoundFile soundFile;
private Timer timer;
private static final int SECONDS = 1000;
/* Name is the name of the alarm.
* Time is the amount of time in seconds until the alarm is suppose to go off.
* SoundFile is the sound that is suppose to play when the alarm goes off.
*/
public Alarm(String name, long time, SoundFile soundFile){
this.name = name;
this.time = time;
this.soundFile = soundFile;
timer = new Timer();
}

public void start(){
timer.schedule(new AlarmTask(), this.time * SECONDS);
}
class AlarmTask extends TimerTask{
public void run(){
//When time is up, Plays the chosen sound file and cancels the timer.
try {
soundFile.play();
} catch (Exception e) {
//Sound file has had a error occur. 
e.printStackTrace();
}
timer.cancel();
}
}

public String getName(){
return name;
}
}


Code 3:
?
package com.kartik.alarm.src.classes;

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class SoundFile {
private String name;
private File file;

/* The name is simply the name of the sound file.
* The pathname is simply the path where the sound file is located.
*/
public SoundFile(String name, String pathname){
this.name = name;
this.file = new File(pathname);
}

public void play() throws Exception{
//Loads the audio files and plays it continuously the user clicks the close button.
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Shows a message dialog box and then closes everything when the user clicks the close button.
JOptionPane.showMessageDialog(null, "Close to stop alarm.");
System.exit(0);
}
});
}

public String getName(){
return name;
}
}



Code 4:
?
package com.kartik.alarm.src.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.joda.time.DateTime;
import org.joda.time.Seconds;

public class AlarmCountDownWindow extends JFrame {
/**

*/
private static final long serialVersionUID = 1L;
public AlarmCountDownWindow(){
initUI();
}
public final void initUI() {

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JLabel alarmNameLabel = new JLabel("Alarm name:");
final JTextField alarmNameTextField = new JTextField();
panel.add(alarmNameLabel);
panel.add(alarmNameTextField);


JLabel alarmTimeLabel = new JLabel("When should the alarm go off from now:");
final String[] hours = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"};
final String[] minutes = new String[61];
final String[] seconds = new String[61];
for(int i = 0; i < minutes.length; i++){
minutes[i] = i+"";
seconds[i] = i+"";
}

/*
* This handles setting up the alarm portion.
*/
JPanel alarmTimePanel = new JPanel();
alarmTimePanel.setLayout(new BoxLayout(alarmTimePanel, BoxLayout.X_AXIS));
JLabel hourLabel = new JLabel("Hour(s):");
final JComboBox<String> hourList = new JComboBox<String>(hours);
JLabel minLabel = new JLabel("Minute(s):");
final JComboBox<String> minList = new JComboBox<String>(minutes);
JLabel secLabel = new JLabel("Second(s):");
final JComboBox<String> secList = new JComboBox<String>(seconds);

alarmTimePanel.add(hourLabel);
alarmTimePanel.add(hourList);
alarmTimePanel.add(minLabel);
alarmTimePanel.add(minList);
alarmTimePanel.add(secLabel);
alarmTimePanel.add(secList);
panel.add(alarmTimeLabel);
panel.add(alarmTimePanel);

//The okay Button.
JButton okayButton = new JButton("Ok");
okayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String alarmName = alarmNameTextField.getText();
//Set the name to a default if the text box was left empty.
if(alarmName.length() == 0){
alarmName = "Alarm";
}
//Get the user settings for the hour, min, and sec.
int hour = Integer.parseInt(hourList.getSelectedItem()+"");
int min = Integer.parseInt(minList.getSelectedItem()+"");
int sec = Integer.parseInt(secList.getSelectedItem()+"");

//Calculate the seconds for the alarm.
DateTime now = DateTime.now();
DateTime dateTime = now.plusHours(hour);
dateTime = dateTime.plusMinutes(min);
dateTime = dateTime.plusSeconds(sec);
Seconds seconds = Seconds.secondsBetween(now, dateTime);

AlarmWindow window = new AlarmWindow(alarmName, seconds.getSeconds());
window.setVisible(true);
}
});
panel.add(okayButton);
//Adds the main panel.
add(panel);

pack();
setTitle("Alarm Settings");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}


Code 5:
?
package com.kartik.alarm.src.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.joda.time.DateTime;
import org.joda.time.Seconds;

public class AlarmTimeWindow extends JFrame{
/**

*/
private static final long serialVersionUID = 3535651838362608675L;
public AlarmTimeWindow(){
initUI();
}
public final void initUI() {

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JLabel alarmNameLabel = new JLabel("Alarm name:");
final JTextField alarmNameTextField = new JTextField();
panel.add(alarmNameLabel);
panel.add(alarmNameTextField);


JLabel alarmTimeLabel = new JLabel("When time should the alarm go off:");
final String[] hours = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
final String[] minutes = new String[60];
for(int i = 0; i < minutes.length; i++){
if(i < 10){
minutes[i] = "0"+i;
}else{
minutes[i] = i+"";
}
}
final String[] m = {"am", "pm"};
/*
* This handles setting up the alarm portion.
*/
JPanel alarmTimePanel = new JPanel();
alarmTimePanel.setLayout(new BoxLayout(alarmTimePanel, BoxLayout.X_AXIS));
JLabel hourLabel = new JLabel("Hour:");
final JComboBox<String> hourList = new JComboBox<String>(hours);
JLabel minLabel = new JLabel("Minute(s):");
final JComboBox<String> minList = new JComboBox<String>(minutes);
JLabel mLabel = new JLabel("Day/Night:");
final JComboBox<String> mList = new JComboBox<String>(m);

alarmTimePanel.add(hourLabel);
alarmTimePanel.add(hourList);
alarmTimePanel.add(minLabel);
alarmTimePanel.add(minList);
alarmTimePanel.add(mLabel);
alarmTimePanel.add(mList);
panel.add(alarmTimeLabel);
panel.add(alarmTimePanel);

//The okay Button.
JButton okayButton = new JButton("Ok");
okayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String alarmName = alarmNameTextField.getText();
//Set the name to a default if the text box was left empty.
if(alarmName.length() == 0){
alarmName = "Alarm";
}
//Get the user settings for the hour, min, and sec.
int hour = Integer.parseInt(hourList.getSelectedItem()+"");
int min = Integer.parseInt(minList.getSelectedItem()+"");
String m = mList.getSelectedItem()+"";
//Calculate the seconds for the alarm.
DateTime now = DateTime.now();
int targetHourOfDay = hour;
//If pass noon add 12 to convert to military time. 
if(m.equals("pm")){
targetHourOfDay += 12;
}
//The target deadline for the alarm to go off.
DateTime dateTime = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), targetHourOfDay, min);


Seconds seconds = Seconds.secondsBetween(now, dateTime);

AlarmWindow window = new AlarmWindow(alarmName, seconds.getSeconds());
window.setVisible(true);
}
});
panel.add(okayButton);
//Adds the main panel.
add(panel);

pack();
setTitle("Alarm Settings");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}


Code 6:
?
package com.kartik.alarm.src.gui;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class MainWindow extends JFrame{


/**

*/
private static final long serialVersionUID = 6493517684652815624L;

public MainWindow(){
initUI();
}

public final void initUI() {

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

panel.setBorder(new EmptyBorder(new Insets(40, 60, 40, 60)));

JButton createCountdownAlarm = new JButton("Create new countdown alarm"), createTimeAlarm = new JButton("Create new time based alarm");

/*
* Sets the action listeners for all of the buttons.
*/
createCountdownAlarm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
AlarmCountDownWindow window = new AlarmCountDownWindow();
window.setVisible(true);
}
});

createTimeAlarm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
AlarmTimeWindow window = new AlarmTimeWindow();
window.setVisible(true);
}
});


panel.add(createCountdownAlarm);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(createTimeAlarm);

add(panel);

pack();

setTitle("Rooster Main Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

}



Code 7:
?
package com.kartik.alarm.src.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.kartik.alarm.src.classes.Alarm;
import com.kartik.alarm.src.classes.SoundFile;


public class AlarmWindow extends JFrame {
private String alarmName;
/**

*/
private static final long serialVersionUID = 7317979646518789994L;
public AlarmWindow(String alarmName, int seconds){
this.alarmName = alarmName;
SoundFile soundFile = new SoundFile("Beep", "D:\\web\\demo\\Demo\\src\\com\\kartik\\alarm\\src\\SoundFiles\\Beep.wav");
Alarm alarm = new Alarm(alarmName, seconds, soundFile);
alarm.start();
initUI();
}
public final void initUI() {

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JLabel alarmNameLabel = new JLabel("Alarm name: "+alarmName);
panel.add(alarmNameLabel);

JLabel notificationLabel = new JLabel("Alarm is set and active");
panel.add(notificationLabel);
//The cancel button. 
JButton cancelButton = new JButton("Cancel/Turn Off Alarm");

cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});

panel.add(cancelButton);
//Adds the main panel.
add(panel);

pack();
setTitle("Alarm");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

}


Alarm set program
Alarm set program




Post a Comment

0 Comments