Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 252
  • Last Modified:

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;
}
0
Drop_of_Rain
Asked:
Drop_of_Rain
  • 18
  • 14
  • 3
4 Solutions
 
objectsCommented:
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();
   }
}
0
 
asood314Commented:
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());
0
 
Drop_of_RainAuthor Commented:
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?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Drop_of_RainAuthor Commented:
asood314:

Thanks I knew that, I'm not clear where to go, read my previous post
0
 
asood314Commented:
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.
0
 
Drop_of_RainAuthor Commented:
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();
   }
}
0
 
asood314Commented:
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.
0
 
Drop_of_RainAuthor Commented:
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));
        }
    }  
0
 
asood314Commented:
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.
0
 
Drop_of_RainAuthor Commented:
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));
0
 
asood314Commented:
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.
0
 
Drop_of_RainAuthor Commented:
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.
0
 
asood314Commented:
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);
    }
}
0
 
objectsCommented:
>    public Fields fields = null;

thats what I mean by keeping a reference to the class (Fields should be replaced with the name of the class that contains the increment mentod).
That allows you to call the increment method in actionPerformed() because you have a referance to the object
0
 
objectsCommented:
>         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
0
 
Drop_of_RainAuthor Commented:
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
   }
}
0
 
Drop_of_RainAuthor Commented:
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.
0
 
asood314Commented:
ok, that code seems fine.  what's your question?
0
 
Drop_of_RainAuthor Commented:
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?
0
 
Drop_of_RainAuthor Commented:
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.
0
 
asood314Commented:
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().
0
 
Drop_of_RainAuthor Commented:
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
   }
}

0
 
asood314Commented:
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.
0
 
Drop_of_RainAuthor Commented:
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
0
 
asood314Commented:
the buttons don't get into TimeAdjuster; when you say

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

you pass the button a reference to a TimeAdjuster object.
0
 
Drop_of_RainAuthor Commented:
Ok,  But how does the adjuster know what field of time  the hour or minute button is?
0
 
asood314Commented:
I thought that was why you were passing the field of time as a parameter is the TimeAdjuster's constructor.
0
 
Drop_of_RainAuthor Commented:
But this was done before there were differents label for each field. This is were I am confused.
0
 
asood314Commented:
what does your new TimeDisplay class look like?
0
 
Drop_of_RainAuthor Commented:
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;
   }
   
0
 
Drop_of_RainAuthor Commented:
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;
}
0
 
asood314Commented:
so what you should do is continue to pass the field of time to TimeAdjuster so that it knows what to update.
0
 
Drop_of_RainAuthor Commented:
I haven't done this before can you show me how to keep doing that?
0
 
asood314Commented:
so it would look something like this:

public void TimeAdjuster implements ActionListener
{
   private DispTime timeDisplay;
   private DispDate dateDisplay;
   private int time_field;
   private int delta;

   public TimeAdjuster(DispTime timeDisplay,DispDate dateDisplay,int time_field, int delta)
   {
       this.timeDisplay = timeDisplay;
       this.dateDisplay = dateDisplay;
       this.time_field = time_field;
       this.delta = delta;
   }

   public void actionPerformed(ActionEvent e)
   {
      if(time_field == Calendar.SECOND || time_field == Calendar.MINUTE || time_field == Calendar.HOUR)
      {
          Calendar time = timeDisplay.getTime();
          time.add(time_field,delta);
          timeDisplay.update(time);
      }
      if(time_field == Calendar.DAY || time_field == Calendar.MONTH || time_field == Calendar.YEAR)
      {
          Calendar date = dateDisplay.getDate();
          date.add(time_field,delta);
          dateDisplay.update(date);
      }
   }
}

i'm assuming here that you have methods to update your displays and get the time or date from your displays as your previous posts have indicated.
0
 
Drop_of_RainAuthor Commented:
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]);

   }
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 18
  • 14
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now