Link to home
Start Free TrialLog in
Avatar of Drop_of_Rain
Drop_of_Rain

asked on

index to JButton?

How would this be connected to a JButton. It goes to a Set button to operate like a Wristwatch. each time it is pressed it advances to the next time field. here HOUR and MINUTE


private int[] AvailableFields = { Calendar.HOUR, Calendar.MINUTE };
private int ActiveFieldIndex = 0;

public int getActiveField()
{
   return AvailableFields[ActiveFieldIndex];
}

public void incrementField()
{
   ActiveFieldIndex = (ActioveFieldIndex + 1) % AvailableFields.length;
}
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of asood314
asood314

also in your gui, you need to add an ActionListener to your JButton. For  example:

JButton button = new JButton("string of your choice");
button.addActionListener(new FieldListener());
Avatar of Drop_of_Rain

ASKER

I have changed everything so much now it feels in a way I'm starting over, but i like it much better. I'm not sure what class will have what at this point. I know I'm having a controller class that will watch the modes, change the buttons and call on the different classes foe each mode. I have changes the GUI I have added a date with 3 labels and the time with 4 label. I have a class for the date and one for the time. I need to get the time adjustment done so i can use that as a model for the timer and the date adjusting.
Should i have a class that handles the time adjustment alone or should the same class handle the adjustment of the time, timer, and date?
asood314:

Thanks I knew that, I'm not clear where to go, read my previous post
That's really just a design call on your part.  Since you already have separate classes for date and time, though, I would probably keep the adjustments separate too.
objects what do you mean by that, I know what the reference is, but the actionlistener is going to be in the GUI class right because that is where the button is. The GUI is referenced in most classes so I should just put them in there right?

How would that be coded?

<have the action listener keep a reference to the class that contains those methods

public class FieldListener implements ActionListener
{
   public Fields fields = null;

   public FieldListener(Fields fields)
   {
      this.fields = fields;
   }

   public void actionPerformed(ActionEvent event)
   {
      fields.incrementField();
   }
}
actually you don't have to make the ActionListener a separate class.  you can have your GUI class implement ActionListener and put your public void actionPerformed() method inside of it.
I like keeping the classes seperate. here is the way it is going for adjusting the time. What i would like to do is have this as a class so it can be called in the timer class. This was for a single label which there is 3 now 1 for the hour and 1 for the minutes and 1 for the am/pm. Woulldn't I be able to do the same thing with the date with this code? This has to be setup to work with the set button that will work for the date. Can this code be used for this as well for the date?

upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.HOUR, 1));
upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.DAY, 1));

    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();
       
        if (cmd.equals(this.guiPanel.hourButton))
        {
           upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.HOUR, 1));
           downButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.HOUR, -1));
        }
        else if (cmd.equals(this.guiPanel.minutesButton))
        {
               upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.MINUTE, 1));
               downButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.MINUTE, -1));
        }
    }  
why are you adding ActionListeners inside your actionPerformed() method?  the whole point of adding ActionListeners is so that actionPerformed can be called when the button is clicked.
This code goes with a class called TimeAdjuster which i'm not sure i'm going to use. It was when the buttons were different. But i like the way of adjusting time this way no formatting. So how would i modify this code to not be working with the actionlistener.

          upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.HOUR, 1));
           downButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.HOUR, -1));
you want to add ActionListeners to your buttons in the constructor fo your gui.  that way when the button is clicked the actionPerformed method of your ActionListener class will be called.  All of the code for adjusting the time should go in your actionPerformed method.
upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay, Calendar.MINUTE, 1));

That much i'm ok with it is making the Calendar.MINUTE, 1, and Calendar.MINUTE, -1  that i need help with for the up button how does that get coded. I haven't seen examples using time adjutment this way.
so say you have JLabel currentMinute, and text "23" or something like that.  In order to increment it by one when upButton is pressed, your actionPerformed method should do something like the following:

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == upButton)
    {
         int min = Integer.parseInt(currentMinute.getText());
         min++;
         currentMinute.setText("" + min);
    }
}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>         if (cmd.equals(this.guiPanel.hourButton))

no you wouldn't need that.
In fact I don't see the pourpose of that entire actionPerformed method.
The buttons are already handled with the TimeAdjuster listener
But i know the works, because objects gave it to me. Calendar.HOUR, 1)); Calendar.HOUR, -1));  here is the class it works with.

public void TimeAdjuster impleemnts ActionListener
{
   private TimeDisplay timeDisplay;
   private int delta;

   public TimeAdjuster(TimeDisplay timeDisplay, int delta)
   {
       this.timeDisplay = timeDisplay;
       this.delta = delta;
   }

   public void actionPerformed(ActionEvent e)
   {
      Calendar time = timeDisplay.getTime();     // get current time displayed
      time.add(timeDisplay.getField(), delta);   // adjust the time
      timeDisplay.update();                      // update display of time
   }
}
objects:>         if (cmd.equals(this.guiPanel.hourButton))

no you wouldn't need that.
In fact I don't see the pourpose of that entire actionPerformed method.
The buttons are already handled with the TimeAdjuster listener

I like the way you code things, more advanced then most in ways. I'm lost because i don't even have a idea of how the buttons are being handled. Can you explain it to me, so I get it. I nerver got to get clear on this part. That is why I looked lost in my coding.
ok, that code seems fine.  what's your question?
objects
That class is not created yet. This app has been changed so much, in a way I'm somewhat starting over just not from scratch. That I would like tio know will this class be able to be used with the date as well? If so then this class of adjusting should be able to be called from each class to do the adjusting, is that right?
I'm raising the point to 500 because this question has become more complex then I though, and both of you are helping me with this question.
The same class should be able to work with the date as long as you have one of your date display objects in the class.  You'd have to change your actionPerformed method a little too.  Basically you'd just have to add something like dateDisplay.update().
What i would like to know is how are the buttons controlled by the TimeAdjuster method. I just don't see it. Maybe something like this?

public void TimeAdjuster impleemnts ActionListener
{
   private TimeDisplay timeDisplay;
   private int delta;

   public TimeAdjuster(TimeDisplay timeDisplay, int delta)
   {
       this.timeDisplay = timeDisplay;
       this.dateDisplay = dateDisplay;
       this.delta = delta;
   }

   public void actionPerformed(ActionEvent e)
   {
      Calendar time = timeDisplay.getTime();     // get current time displayed
      time.add(timeDisplay.getField(), delta);   // adjust the time
      timeDisplay.update();               // update display of time
      dateDisplay.update().               // update display of date
   }
}

it works like this.  when you say

upButton.addActionListener(new TimeAdjuster(guiPanel.timeDisplay,Calendar.MINUTE,1));

a TimeAdjuster is made for that button.  Then whenever that button is clicked, the actionPerformed() method of that TimeAdjuster is called.  That's how the button interacts with the TimeAdjuster.
But how is the buttons for the hour and minutes getting into it? There are a hour, minute, up and down buttons on the GUI for time
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok,  But how does the adjuster know what field of time  the hour or minute button is?
I thought that was why you were passing the field of time as a parameter is the TimeAdjuster's constructor.
But this was done before there were differents label for each field. This is were I am confused.
what does your new TimeDisplay class look like?
As you will se below it use to be set up for 1 label timeDisplay. I have a class just like this for the Date.

import javax.swing.*;
import java.awt.Frame;
import java.awt.Container;
import java.util.Formatter;
import java.util.GregorianCalendar;

public class DispTime extends JFrame implements Runnable
{
   GregorianCalendar clockCalendar;
   JLabel day;
   JLabel month;
   JLabel year;
   Thread t;
   int i;
 
   DispDate()
   {

      t = new Thread(this);
      t.start();
   }


   public void run() {
        while(runner != null) {
            clockCalendar = new GregorianCalendar();

            currentDay = clockCalendar.get(Calendar.Day);
            currentMonth = clockCalendar.get(Calendar.MONTH);
            currentYear = clockCalendar.get(Calendar.YEAR);
             
              day.setText("" + currentDay");
            month.setText(""  + currentMonth );
            year.setText(""  + currentYear);
              

            try {
             
            } catch(InterruptedException interruptedexception) { }
        }
    }



   public static void main(String[] args)
   {
     
      final NewDispDate PRN = new NewDispDate();
      final GuiPanel gp = new GuiPanel();
      PRN.setDispListener(gp.getDateDisplay());

      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            gp.setVisible(true);
         }
      });

   }


   /**
    * @param dateDisplay
    */
    void setDispListener(JLabel dateDisplay)
   {
      this.listenerTF = dateDisplay;
   }
   
Sorry wrong class:

import javax.swing.*;
import java.awt.Frame;
import java.awt.Container;
import java.util.Formatter;
import java.util.GregorianCalendar;

      public class DispTime extends JFrame implements Runnable
{
   GregorianCalendar clockCalendar;
   JLabel hours;
   JLabel minutes;
   JLabel seconds;
   JLabel amPm;
   Thread t;
   int i;
 
   DispTime()
   {

      t = new Thread(this);
      t.start();
   }


   public void run() {
        while(runner != null) {
            clockCalendar = new GregorianCalendar(currentTimeZone);
            if(hourFormat == 24)
                currentHour = clockCalendar.get(Calendar.HOUR_OF_DAY);
            else
            currentHour = clockCalendar.get(Calendar.HOUR);
            currentMinute = clockCalendar.get(Calendar.MINUTES);
            currentSecond = clockCalendar.get(Calendar.SECONDS);
          currentAmPm = clockCalendar.get(Calendar.AM_PM);
             
              hours.setText("" + currentHour");
            minutes.setText(""  + currentMinute );
            seconds.setText(" "  + currentSecond);
              
              if(Calendar.AM_PM == Calendar.AM) {
                 amPm.setText("am");
            }
            else{
               amPm.setText("pm");
            }

            try {
                Thread.sleep(1000L);
            } catch(InterruptedException interruptedexception) { }
        }
    }


   public static void main(String[] args)
   {
     
      final NewDispTime PRN = new NewDispTime();
      final GuiPanel gp = new GuiPanel();
      PRN.setDispListener(gp.getTimeDisplay());

      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            gp.setVisible(true);
         }
      });

   }


   /**
    * @param timeDisplay
    */
    void setDispListener(JLabel timeDisplay)
   {
      this.listenerTF = timeDisplay;
   }
   
   private JLabel listenerTF;
}
so what you should do is continue to pass the field of time to TimeAdjuster so that it knows what to update.
I haven't done this before can you show me how to keep doing that?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK I am pushing myself and you. Ok I understand your code. I see that it excepts all fields in time and date. The way my app works is this in general. It is a GUI with a time display with 4 labels, a date display with 3 labels, 10 buttons a mode,ok,hour,minute,record,play,set,stop, up. down. and a  mode display. It will function like a wristwatch. When the mode is set to alarm and the hour button is pressed the hour display starts to blink and the user uses the up and down button to move the time to their desired time. When they are finished they press the ok button. That time will be converted to milliseconds and starts a timer, when the timer runs out it plays an alarm audio file and then a message audio file.There is also a timer mode that works the same way except the numbers start at 0 in the displays. that time starts a timer as well. There is a stopwatch, and audio recorder, and player. this is just to give you a little idea of what it is that you are helping me with.

Here are the methods:

   public javax.swing.JLabel getTimeDisplay()
   {
      JLabel timeDisplay = new JLabel(hours.getText() + ":" + minutes.getText() + ":" + seconds.getText() + ":"  + amPm.getText());
      return timeDisplay;
   }

   public void setTimeDisplay(javax.swing.JLabel timeDisplay)
   {
      String [] arr = timeDisplay.split(":");
      currentHour.setText(arr[0]);
      currentMinute.setText(arr[1]);
      currentSecond.setText(arr[2]);
      currentAmPm.setText(arr[3]);
   }

   public javax.swing.JLabel getDateDisplay()
   {
      JLabel dateDisplay = new JLabel(day.getText() + ":" + months.getText() + ":" + year.getText());
      return dateDisplay;
   }

   public void setDateDisplay(javax.swing.JLabel dateDisplay)
   {
      String [] arr = dateDisplay.split(":");
      currentDay.setText(arr[0]);
      currentMonth.setText(arr[1]);
      currentYear.setText(arr[2]);

   }