Alterations to inputs in a Java application

Hi folks, I'm trying to do a clock that has an alarm feature and it's all working fine, but I want the input to work as an select input instead of the current text field. Now there is only one input since I couldn't make it to show three fields in a single "JOptionPane.showInputDialog", the input must be typed like this: "10:45:AM" indicating the hour:minutes:timeOfDay so that the program can parse it and change it into "int".

If it could be done I wanted to offer three select fields which could choose hour, minute and AM/PM for the alarm, but for some reason I can't seem to make it work...

Here are the files:
Clock Class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.lang.String;

/**
 * 
 * @author Rodrigo de Oliveira Costa
 * @studentId 2141030
 * @version 7.0
 * @paper Software Development
 * @tutor Andrew Eales
 * 
 */
public class Clock
{
    private JFrame frame;
    private JLabel label;
    private ClockDisplay clock;
    private boolean clockRunning = false;
    private boolean alarmSet = false;
    private TimerThread timerThread;
    private int hours;
    private int minutes;
    private String pmAm;
    
    /**
     * Constructor for objects of class Clock
     */
    public Clock()
    {
        makeFrame();
        clock = new ClockDisplay();
    }
    
    private void start()
    {
        clockRunning = true;
        timerThread = new TimerThread();
        timerThread.start();
    }
    
    public void setAlarm( int hour, int min, String AMPM )
    { 
        hours = hour;
        minutes = min;
        pmAm = AMPM;
        alarmSet = true;
    }
    
    private void stop()
    {
        clockRunning = false;
    }
    
    /**
     * 
     */
    private void step()
    {
        clock.timeTick();
        label.setText(clock.getTime());
        if( alarmSet == true && hours == clock.getHours() && minutes == clock.getMinutes() && pmAm.equals(clock.getAmPm()))
        {
            if( clock.getSeconds() % 2 == 0 )
            {
                label.setForeground(Color.red);
                Toolkit.getDefaultToolkit().beep();  
                stop();
            }
            else 
                label.setForeground(Color.black);
                Toolkit.getDefaultToolkit().beep();  
        }
    }
    
    /**
     * 'About' function: show the 'about' box.
     */
    private void showAbout()
    {
        JOptionPane.showMessageDialog (frame, 
                    "Clock Version 7.0\n" +
                    "Modification of the example provided on the book with the Assignment One requirements.",
                    "About Clock", 
                    JOptionPane.INFORMATION_MESSAGE);
    }
    
    /**
     * Quit function: quit the application.
     */
    private void quit()
    {
        System.exit(0);
    }

    /**
     * Create the Swing frame and its content.
     */
    private void makeFrame()
    {
        frame = new JFrame("Clock");
        JPanel contentPane = (JPanel)frame.getContentPane();
        contentPane.setBorder(new EmptyBorder(1, 60, 1, 60));

        makeMenuBar(frame);
        
        // Specify the layout manager with nice spacing
        contentPane.setLayout(new BorderLayout(12, 12));
        
        // Create the image pane in the center
        label = new JLabel("00:00:00 AM", SwingConstants.CENTER);
        Font displayFont = label.getFont().deriveFont(96.0f);
        label.setFont(displayFont);
        //imagePanel.setBorder(new EtchedBorder());
        contentPane.add(label, BorderLayout.CENTER);

        // Create the toolbar with the buttons
        JPanel toolbar = new JPanel();
        toolbar.setLayout(new GridLayout(1, 0));
        
        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { start(); }
                           });
        toolbar.add(startButton);
        
        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { stop(); }
                           });
        toolbar.add(stopButton);

        JButton stepButton = new JButton("Step");
        stepButton.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { step(); }
                                
                            });
        toolbar.add(stepButton);
                                    
        
                            
        // Add toolbar into panel with flow layout for spacing
        JPanel flow = new JPanel();
        flow.add(toolbar);
        
        contentPane.add(flow, BorderLayout.SOUTH);
        
        // building is done - arrange the components      
        frame.pack();
        
        // place the frame at the center of the screen and show
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
        frame.setVisible(true);
    }
    
    /**
     * Create the main frame's menu bar.
     * 
     * @param frame   The frame that the menu bar should be added to.
     */
    private void makeMenuBar(JFrame frame)
    {
        final int SHORTCUT_MASK =
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);
        
        JMenu menu;
        JMenuItem item;
        
        // create the File menu
        menu = new JMenu("File");
        menubar.add(menu);
        
        item = new JMenuItem("About Clock...");
            item.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { showAbout(); }
                           });
        menu.add(item);

        item = new JMenuItem("Alarm");
            item.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { Object[] possibilities = {null};
                                String string = (String)JOptionPane.showInputDialog(
                                frame,
                                "To set the alarm please enter hours, minutes and AM/PM seperated by ':'\n"
                                + "\"eg. 10:10:AM\"",
                                "Set Alarm",
                                JOptionPane.PLAIN_MESSAGE);
                                String[] parts = string.split(":");
                                String part1 = parts[0]; 
                                String part2 = parts[1];
                                String part3 = parts[2].toUpperCase();
                                int h = Integer.parseInt(part1);
                                int m = Integer.parseInt(part2);
                                setAlarm( h, m, part3 );
                               
                            };
                           });
        menu.add(item);
        menu.addSeparator();
        
                
              
        item = new JMenuItem("Quit");
            item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
            item.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { quit(); }
                           });
        menu.add(item);
    }
    
    class TimerThread extends Thread
    {
        public void run()
        {
            while (clockRunning) {
                step();
                pause();
            }
        }
        
        private void pause()
        {
            try {
                Thread.sleep(10);   // pause for 300 milliseconds
            }
            catch (InterruptedException exc) {
            }
        }
    }
}

Open in new window

NumberDisplay



/**
 * The NumberDisplay class represents a digital number display that can hold
 * values from zero to a given limit. The limit can be specified when creating
 * the display. The values range from zero (inclusive) to limit-1. If used,
 * for example, for the seconds on a digital clock, the limit would be 60, 
 * resulting in display values from 0 to 59. When incremented, the display 
 * automatically rolls over to zero when reaching the limit.
 * 
 * @author Michael Kölling and David J. Barnes
 * @version 2011.07.31
 */
public class NumberDisplay
{
    private int limit;
    private int value;

    /**
     * Constructor for objects of class NumberDisplay.
     * Set the limit at which the display rolls over.
     */
    public NumberDisplay(int rollOverLimit)
    {
        limit = rollOverLimit;
        value = 0;
    }

    /**
     * Return the current value.
     */
    public int getValue()
    {
        return value;
    }

    /**
     * Return the display value (that is, the current value as a two-digit
     * String. If the value is less than ten, it will be padded with a leading
     * zero).
     */
    public String getDisplayValue()
    {
        if(value < 10) {
            return "0" + value;
        }
        else {
            return "" + value;
        }
    }

    /**
     * Set the value of the display to the new specified value. If the new
     * value is less than zero or over the limit, do nothing.
     */
    public void setValue(int replacementValue)
    {
        if((replacementValue >= 0) && (replacementValue < limit)) {
            value = replacementValue;
        }
    }

    /**
     * Increment the display value by one, rolling over to zero if the
     * limit is reached.
     */
    public void increment()
    {
        value = (value + 1) % limit;
    }
}

Open in new window

ClockDisplay


import java.util.*;
/**
 * The ClockDisplay class implements a digital clock display for a
 * European-style 24 hour clock. The clock shows hours and minutes. The 
 * range of the clock is 00:00 (midnight) to 23:59 (one minute before 
 * midnight).
 * 
 * The clock display receives "ticks" (via the timeTick method) every minute
 * and reacts by incrementing the display. This is done in the usual clock
 * fashion: the hour increments when the minutes roll over to zero.
 * 
 * @author Michael Kölling and David J. Barnes
 * @version 2011.07.31
 */
public class ClockDisplay
{
    private NumberDisplay hours;
    private NumberDisplay minutes;
    private NumberDisplay seconds;
    String amPm;
    private String displayString;    // simulates the actual display
    
    /**
     * Constructor for ClockDisplay objects. This constructor 
     * creates a new clock set at 00:00.
     */
    public ClockDisplay()
    {
        hours = new NumberDisplay(13);//Check this since its going over 12...
        minutes = new NumberDisplay(60);
        seconds = new NumberDisplay(60);
        
        Calendar time = new GregorianCalendar();
        if(time.get(Calendar.HOUR) == 00)
        {
            hours.setValue(12);
            minutes.setValue(time.get(Calendar.MINUTE));
            seconds.setValue(time.get(Calendar.SECOND));
        }
        else
        {
            hours.setValue(time.get(Calendar.HOUR));
            minutes.setValue(time.get(Calendar.MINUTE));
            seconds.setValue(time.get(Calendar.SECOND));
        }
        
        if(time.get(Calendar.AM_PM) == 0)
        {
            amPm = "AM";
        }
        else
        {
            amPm = "PM";
        }
        updateDisplay();
    }

    /**
     * Constructor for ClockDisplay objects. This constructor
     * creates a new clock set at the time specified by the 
     * parameters.
     */
    public ClockDisplay(int hour, int minute, int second)
    {
        hours = new NumberDisplay(24);
        minutes = new NumberDisplay(60);
        seconds = new NumberDisplay(60);
        setTime(hour, minute, second);
    }
    
    /**
     * This method should get called once every minute - it makes
     * the clock display go one minute forward.
     */
    public void timeTick()
    {
        seconds.increment();
        if(seconds.getValue() == 0){ // it just rolled over!
            minutes.increment();
            if(minutes.getValue() == 0){  // it just rolled over!
                hours.increment();
                 if(hours.getValue() == 0 )
                {
                    if(amPm == "AM")
                    {
                        amPm = "PM";
                    }
                    else
                    {
                        amPm = "AM";
                    }
                }
            }
        }
        updateDisplay();
    }

    /**
     * Set the time of the display to the specified hour and
     * minute.
     */
    public void setTime(int hour, int minute, int second)
    {
        hours.setValue(hour);
        minutes.setValue(minute);
        seconds.setValue(second);
        updateDisplay();
    }

    /**
     * Return the current time of this display in the format HH:MM.
     */
    public String getTime()
    {
        return displayString;
    }
    
    /**
     * Update the internal string that represents the display.
     */
    private void updateDisplay()
    {
        displayString = hours.getDisplayValue() + ":" + 
                        minutes.getDisplayValue() + ":" +
                        seconds.getDisplayValue() + amPm;
    }
    
    public int getHours()
    {
        return hours.getValue();
    }
    
    public int getMinutes()
    {
        return minutes.getValue();
    }
    
    public int getSeconds()
    {
        return seconds.getValue();
    }
    
    public String getAmPm()
    {
        return amPm;
    }
}

Open in new window


Any help would be much appreciated.

Cheers.
Rodric MacOliverResearcherAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
JOptionPane is only meant to cater for the most common dialog box scenarios. While it does have a great deal of flexibility, it can't handle EVERY sort of situation that one might need.

So the solution is... just use JDialog (which JOptionPane uses internally anyway) and build your dialog box UI just as you would a normal window in a GUI application. The only real defference is that JDialog is used instead of JFrame, but you can add components, etc to the JDialog's content pane just like you can with JFrame.
0
zzynxSr. Software engineerCommented:
None of your classes contains a main() method. How do you run this?
0
Tomas Helgi JohannssonCommented:
Hi!

You could do this something like this.

import javax.swing.JOptionPane;
public class InputDialogWithDropdownListbox {
  public static void main(String[] a) {
  
    
    String hours[] = new String[12];
    String minutes [] = new String[60];
    String[] timeofday = { "AM", "PM" };
    for (int i = 0; i < hours.length; i++) {
          hours[i] = Integer.toString(i);
    }
    for (int i = 0; i < minutes.length; i++) {
              minutes[i] = Integer.toString(i);
    }
 
    Object complexMsg[] = { "Choose your time",hours , minutes,
        timeofday, "Some text"};
   JOptionPane optionPane = new JOptionPane();
       optionPane.setMessage(complexMsg);
       optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
       JDialog dialog = optionPane.createDialog(null, "Width 100");
    dialog.setVisible(true);
  }
}

Open in new window


Note this code is not tested.

Regards,
      Tomas Helgi
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
If you're keen to use JOptionPane, make a JPanel containing your combos with suitable accessor methods for the choices. That panel then becomes the second parameter (when using the two parameter call) to JOptionPane.showMessageDialog
0
CEHJCommented:
How have you got the three separate time criteria from that code and used them?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.