Friday, January 9, 2015

Java StopWatch: making the buttons move

Making textbox output is a bit of a pain, but it's not that terribly hard.

Here's a picture of the design for reference.  I still need to figure out how to center the items in the GridLayout().


I ended up writing a separate private subclass to implement the minutes up button.  So...  how does it work?

You start with a string as the current text box output.

String txt = minutes.getText();
char characters[] = txt.toCharArray();

Now, I could probably cram this on to one line, but I don't think I am.  I like the simplicity of the statement, and it's not that complex or hard to understand.  

So, now we've got a character array holding what is displayed in our minutes field on screen.  Where to next?  

I need to convert those to integers.

int ones = characters[1] - '0';
int tens = characters[0] - '0';

Simple enough?   Take whatever the unicode letter is and subtract it from the unicode character '0'.   Simple math, and then you have the ones and tens place.

As a side note, I learned the last bit back in 2000 when I was learning C++.  I have since fallen out of use in C++, but I still remember that trick to get a number out of a character.

Ok.  Now we know what our number is.   We need to increase it.  

Simple enough.

ones = ones + 1;

if(ones >= 10)
{
     ones = 0;
     tens += 1;


Easy enough to understand, I hope?   + 1 to the ones place.  The ones place can't be greater than 9, so if it gets bigger than or equal to 10, then make it zero and increment the tens.

That will give us a stop watch that will increase up to 99 minutes.

And for the final bit, pushing the new number back into the JTextBox

minutes.setText( Integer.toString(tens) + Integer.toString(ones));

After the rest of the complications, this one is easy.

I haven't written the code for converting seconds, but that is also simple enough.  The only question is what you do when you reach 59 seconds.  Do you go back to 0, or do you increase the minutes by 1 and go to 0?  

Either way can be done.  It's just a personal preference.  Generally, I count up minutes and seconds.  Though come to think about it, I count up every time and only could down seconds.  So my program is inconsistent.  I think with this one, I'll just make the seconds rotate.  It's another simple if/else comparison.  

But yeah, that's about it for the up buttons.  For seconds, just swap a few names.  The down arrow works pretty much the same way, except it decrements.  

As a random thought, I have thought about trying to cram the minutes/seconds up buttons into one class.  I'm sure it's possible, I just don't have the skill.   Essentially, both would have to have a separate actionPerformed, and I'm not sure how to do that.  


No comments:

Post a Comment