Learning Java: Day 13

Working With Swing Components

Component is the more correct term for what I've been referring to as widgets. Those are the things you put in a GUI, or the things that the user sees and interacts with. Almost every thing you can stick in a GUI extends from javax.swing.JComponent.

Chapter 13 of Head First Java covers the layout managers for JPanel and JFrame, creating scrollbars on textboxes, making lists, and finally, creating the BeatBox midi player.

Fact 1: Different layout managers have different policies and you have to memorize what they are if you want your buttons/textboxes/lists/etc to be placed where you actually want them to be.

Fact 2: BorderLayout is the default layout manager for a frame; FlowLayout is the default for a panel.

Fact 3: When you add a component to another component, the added component is controlled by the layout manager of the background component.

Three layout managers: border, flow, and box.
BorderLayout: the BorderLayout manager divides a background component into five regions (NORTH, SOUTH, EAST, WEST, CENTER). You can only add one component per region to a background controlled by a BorderLayoutManager. This is the default layout manager for a frame.

FlowLayout: the FlowLayout manager lays out components from left to right, top to bottom, in the order they were added, wrapping to a new line when needed. This is the default layout manager for a panel.

BoxLayout: the BoxLayout manager places components from top to bottom, one per line.

Most of my time spent in this chapter was typing the code for the BeatBox and then debugging it prior to compiling. Debugging might be the most useful skill I'll learn as I work my way through the book.

School is starting on September 8th.  I still have 5 more chapters and 2 appendices to work through before school begins.  I've gotta work faster!

Learning Java: Day 12

Do It Yourself Graphical User Interfaces

Chapter 12 of Head First Java  goes over the ins and outs of creating GUIs - Graphical User Interfaces. We learn to deal with Event Handling and Inner Classes while moving from command line inputs and outputs to creating our first graphical anything.

This chapter has taken me four days to get through; in part because it's a long chapter, partly because I've been busy with the house and family, but mostly because it's been difficult for me to understand.  Not to mention my self-induced buggy code. On the other hand, I'm getting MUCH better at debugging my code.

To make a very long story short:

Import the javax.swing package when you want to put a window on the computer screen.
JFrame is what makes a window to put your widget (button, text field, image, over a dozen different types) on.

An Event is what happens when the user does something with the screen widget (i.e. clicks a button.)

Each widget needs a Listener to tell the class that an event occurred.

Import java.awt.* when you want to use the java Graphics components for drawing, filling, setting colors, and manipulating those aspects of 2D drawing.

If you want more than one widget in a window, use Inner classes.

We created three versions of the midi player:
  1. The player gave a sound-only output of ascending piano notes.
  2. The player gave an output of ascending piano notes while printing "la" in the command window for each note that was played.
  3. A new window was created with a randomly placed rectangular box with randomly selected fill-color for each randomly selected piano note (64 times)
Yay! I'm finally creating graphics and sound!  It's still a little foggy but it's a start!




Learning Java: Day 11

Exception Handling
Anytime you work with computers, stuff happens. The server is down. The network is offline. The file is corrupted.  As a programmer you need to write code that can handle the bad times; problem-handling code for when you can't guarantee that the file will be in the right directory, the server will be up and running, or the Thread stays asleep. Chapter 11 of Head First Java covers this kind of problem anticipation.

We will be building a MIDI Music Player.  Over the next three chapters we'll learn to create a graphical user interface (GUI) and a multi-user BeatBox Drum Machine. Today we learn what is required to create a MIDI player and how to handle exceptions.

Risky Business
When your code calls a risky method -- a method that declares an exception -- it's the risky method that throws the exception back to you, the caller. You have to read the API docs to see if there is risky behavior in the code.  The method has to declare the exceptions it might throw. The API docs then tell you WHEN you might get that exception, such as resource restrictions because the object (in this case, the sequencer) might already be in use. It's up to you to write code to deal with the problem.

Checked Exception vs RuntimeException
RuntimeExceptions occur because you've got flaws in your code that need to be fixed before the code will compile.
Checked Exceptions happen while the program is running and are caused when a method throws an exception with the keyword throw,  followed by a new exception object:
     throw new noJuiceFastException();
Methods that might throw a checked exception must announce it with a throws Exception declaration. Methods can throw more than one exception.

Try/Catch
A try/catch block tells the compiler that you know an exceptional thing could happen in the method you're calling, and that you're prepared to handle it. The compiler doesn't care how you handle it; it cares only that you say you're taking care of it.

  • Exceptions are polymorphic
  • Write a different catch block for each exception that you need to handle uniquely.
  • Multiple catch blocks must be ordered from smallest to biggest.
Making Sounds
You need four things:
  1. Sequencer: The thing that plays the music
  2. Sequence: The music to be played...a song
  3. Track: The part of the Sequence that holds the actual information
  4. Midi Event: The actual music information (notes to play, how long, etc.)
Today we use command line arguments to experiment with sounds. Next chapter we create MIDI events using a very crude video that pulses to the beat of the MIDI music. 

Onward...

Speedy Pasta Skillet Recipe

Saturdays are busy days around our house. House-cleaning, laundry, bed-linen-changing, ironing; it's a day that calls for easy meals. This recipe is one I learned to make as a young teenager and have fed to my own family as the kids grew up.  It's always been a family favorite; it's tasty, cheap, quick to make, and can be modified to use whatever you have on hand.  It's a great main dish when you're too pooped to put much effort into cooking.

This recipe takes about 1/2 hour to make if you boil the noodles at the same time you cook the ground beef. It will feed about 5-6 people if you include a salad and another side dish.

Speedy Pasta Skillet
1 pound ground beef
1 cup onion, chopped
1 clove garlic, minced
1/2 cup green onion, chopped (optional)
1 cup eggplant, peeled and chopped (optional)
1 teaspoon oregano (optional)
1 teaspoon parsley flakes (optional)
Salt and pepper to taste
1 6-oz can tomato paste
1 cup grated cheese (optional)

1 pound rigatoni pasta, cooked to al dente

chopped tomatoes and cilantro for garnish (optional)
grated Parmesan cheese (optional)

Set a large pot of heavily salted water on the stove at high heat.  When the water comes to a boil add your pasta.  Turn the heat down to medium and allow the pasta to boil until it's still a little firm (al dente). Stir occasionally to keep the pasta from sticking to the bottom of the pan. Drain.

In the meantime, brown the ground beef, onions, green pepper, garlic and eggplant together in a large skillet. Drain any excess fat from the skillet. Season with the herbs and salt and pepper to taste. Add tomato paste to the meat and mix well.  Add the grated cheese and mix again.  Add the drained pasta to the meat and mix well.  If desired, garnish with chopped tomatoes, cilantro, and grated Parmesan cheese. 

Notes: All of the optional items are additions to the original recipe. You can use any kind of pasta: elbows, shells, wheels, tubes, whatever you have on hand.  Use any vegetable that your family likes. I've used peas instead of eggplant.  A relative uses frozen lima beans. Chopped kale, chard, or spinach would be lovely. Substitute Italian sausage for the ground beef. Use a pound of chopped mushrooms instead of ground beef for a vegetarian version. Use cheddar, mozzarella, Monterey Jack, Swiss, or something entirely different for the cheese or don't use any cheese at all. The variations are endless.

Learning Java: Day 10

Numbers and Statics
We are what we repeatedly do.  Excellence then, is not an act, but a habit.
- Aristotle
Today marks the halfway point in the book, Head First Java. Yesterday I was wondering why I was so determined to learn this programming language, especially since it is not even remotely similar to my upcoming Master's degree studies of acupuncture and Oriental medicine. Java is difficult for me to learn and frequently I've felt really, really dumb because it's taken so long to wrap my mind around some of the concepts. I've told people who've asked me why I'm bothering to learn programming, that I want to be able to create Android phone apps for use in my master's studies, so therefore I need to know Java (since the phone apps are created in Java). But I think the answer lies deeper than that. 

I want to learn Java because it's difficult for me.  I want to conquer this subject. I want to learn Java because it's just one of the many things I want to learn or do before I die. So let's get on with it...
______________________________________
STATIC
The keyword static lets a method run without any instance of the class.  This is used when you don't need to have an instance of the class (like when using the Math methods). 

You call a static method using the class name

Example:     Math.min(66,99);
You call a non-static method using a reference variable name
Example:     Werewolf Jacob = new Werewolf();
          Jacob.howl();

Static variable: value is the same for All instances of the class.
Static variables are shared.
All instances of the same class share a single copy of the static variables.
Instance variables: 1 per instance
static variables: 1 per class

FINAL means it can never change
A final variable means you can't change its value.
A final method means you can't override the method.
A final class means you can't extend the class (i.e. you can't make a subclass).

MATH
Converting a String to a primitive value ('parseInt', 'parseDouble', or 'parseBoolean'): 
     String s = "2";
     int x = Integer.parseInt(s);

Converting a primitive number into a string (easiest way is to concatenate the number to an existing string)
     double d = 42.5;
     String doubleString = " " + d;

     double d = 42.5;
     String doubleString = Double.toString(d);

FORMAT
%,d means "insert commas and format the number as a decimal integer."
%.2f means "format the number as a floating point with a precision of two decimal places."
%,.2f means "insert commas and format the number as a floating point with a precision of two decimal places."
Formatting Dates (Use java.util.Date when you want the current date and time):
%tc gives the complete date and time: String.format ("%tc", new Date()); 
          Fri Aug 17 23:58:29 HST 2012
%tr gives just the time: String.format ("%tr", new Date());
          11:58:29 PM
%tA %tB %td gives the Day of the week, month and day
     Date today = new Date();
     String.format ("%tA, %tB, %td", today,today,today)(there's an easier way but I can't get it to format correctly on this screen)
                    Friday, August 17

Use java.util.Calendar for date manipulation.
There are a LOT of methods in the Calendar API and a lot of Calendar Fields.
And we finally end with practice and exercises.  This was a very LONG chapter. My brain is fried...


Learning Java: Day 9

Constructors and the Garbage Collection
Have you ever run a software program that slowed down after you'd been working for a while, and it got so bad that you had to close the application and restart it in order to continue working?  That's what happens when the programmer doesn't pay close attention to getting rid of objects when those objects are done doing "its thing".  Those abandoned objects continue taking up RAM, so much so that eventually you run out of memory space and have to close the program in order to free the memory space up again.  Java automatically takes out the trash for you.

Chapter 8 of Heads Up Java covers how objects are created, where they live while they're alive, and how to keep or abandon them efficiently.

There are two areas of memory that are important in Java; the Stack and the Heap. 

The Heap is also known as "The Garbage Collectible Heap".  The Heap is where ALL, ALL, ALL objects live. The instance variables that belong to the object live inside their objects on the heap, too. 

The Stack is where method invocations (like go() and doStuff() and main()) along with local variables live. A local variable is alive until its method completes. A local variable is in scope only within the method in which the variable was declared.  You can only use that local variable while its method is actually running.  As soon as the method is completed, the variable is popped off the Stack and goes into garbage collection.

How Objects Are Created
  1. Declare a reference variable:                     Dog myPuppy = new Dog();
  2. Create an object                                      Dog myPuppy = new Dog();
  3. Link the object and the reference            Dog myPuppy = new Dog();

Constructors
A constructor looks and feels a lot like a method, but it's not a method.  It's got the code that runs when you say new. It's the code that runs when you instantiate an object. The thing that separates a method from a constructor is the return type. Methods must have a return type, but constructors cannot have a return type.

Overloaded constructors means you have more than one constructor in your class.  To compile, each constructor must have a different argument list.

How Long Does an Object Live?
An object's life depends exclusively on the life of the references referring to it.  If the reference is considered alive, the object is still alive on the Heap.  If the reference dies, the object will die and will be picked up by garbage collection.

3 ways to get rid of an object's reference:
  1. The reference goes out of scope, permanently 
    •  // the reference dies at the end of the method
  2. The reference is assigned another object       
    •  // the first object is abandoned when the reference moves
  3. The reference is explicitly set to null       
    •  // the first object is abandoned when the reference is 'deprogrammed'.
This chapter end with exercises, a puzzle and a five-minute mystery.

Hiking Oahu: Aiea Loop Trail

This is the beginning of my hiking series.  My health has improved since doing the juice fast so I've been increasing my exercise levels. I'd like to write weekly about different hikes around Oahu.  The Aiea Loop Trail is my first hike.
Aiea Loop Trail
Distance: 4.8 miles
Level: Easy
Time: 2 -3 hours if you are in relatively good shape
Location: At the end of Aiea Heights Drive. Follow H-1 to Moanalua Highway (Hwy 78). Take the Aiea cutoff to the third traffic light, make a right turn at Aiea Heights Drive and follow it about 3 miles up to the end of the road.
Hours: April 1 to Labor Day: 7 a.m. to 7:45 p.m
After Labor Day to March 31: 7 a.m. to 6:45 p.m.
Entrance Fees: None
Services/Facilities: Restrooms, showers, camping area, picnic tables, trash cans, drinking water, payphone, hiking trail.
Caveats: Go on a sunny day, otherwise wear boots and clothes you don't mind getting muddy.  Take drinking water. Although it is ranked easy, the trail is uneven with crisscrossing tree roots, many fallen trees that you have to cross over or go under, and there is about 1/2 mile of muddy trail even on the driest days.
Keaiwa heiau (photo from Wikipedia)

Yesterday was a sunny, cool day; perfect for hiking the Aiea Loop Trail.  This trail is located in the Kea'i'wa Heiau State Recreation Area. The Kea'i'wa Heiau is at the park entrance.

This particular heiau was a place of healing where illnesses and injuries were treated with herbs by the kahuna and his students. The heiau is thought to have been constructed in the 16th century by the Oahu chief Kahuhihewa and his kahuna Keaiwa. The 100' x 160' area is enclosed by a 4' high wall of stacked lava rock. The central halau (large thatched structure) is no longer there.

The trail is not particularly scenic although there are several spots where the forest clears and you can see out into the distance.  Most of the time you are hiking through forests. Much of the fun comes from noticing the changes in the forest types.  We counted 9 distinct forests. 

Distinct Forests on the Trail
Eucalyptus: is at the very beginning of the hike and the air is redolent with the citrus-y/menthol smell of eucalyptus. The trail is dry and easy at this point.

unripe strawberry guavas
ripe strawberry guavas
Strawberry Guava: I think this was the second forest we passed through. These plants are considered an invasive species but they provide yummy snacks along the way.  The majority of the plants held green fruit but I found several bushes that had ripe berries.  I think that most of the fruit will be ripe in October. The trail was dry and easy through this section.
Huge koa trees
twisted but alive Koa

Koa: The koa forests repeated a few times on the hike. The trees were huge, straight-trunked monsters in the protected areas and twisted, gnarled grandfathers on the windy ridges. The straight trees appeared to be over 100 feet tall. These must have been the types that were cut down and hauled off the mountains to be made into canoes.  Some of them seemed to be the girth of 4 large men.  The gnarled trees frequently had most of their foliage missing but managed to keep some growth going.
Hapu'u
Uluhe (false staghorn fern): These native ferns create thick mats of vegetation that prevent invasive plants from taking hold.  They cover entire hillsides along the trail.
Hapu'u Fern: The indigenous hapu'u were definitely not as well-represented as the hill-covering uluhe, but there were spots where they were relatively thick. Instead of crowding out other plants, the hapu'u seemed to happily share their space.

Lemon Guava: These guys fooled me at first.  I thought they were really old strawberry guava trees.  The mature trees were 30 to 40 feet tall and their leaves were about twice the size of their strawberry cousins.  The fruit were slightly larger than the strawberry guys but still tasty.
Norfolk pines

Norfolk Pine:  Gorgeous growths of these pines are found in several places along the trail. Their seeds were sprinkled all over the younger trees from the older ones above.  Seeds cover the trail in places.
Ohi'a lehua

Ohia Lehua: Another native, the lehua shows up in a couple places along the trail.  Several of the trees are pretty majestic-looking though it's hard to tell from the photo.

Bamboo: There was only one section, I think, where there was a concentration of bamboo.

yellow ginger
Kukui: These beautiful trees were mainly concentrated close to the bottom of the valley near the stream bed along with the Yellow Ginger. I could smell the ginger before I saw them.

There was about a 1/2 mile stretch of very wet trail before getting to the stream bed and then isolated spots going back up the trail.  Amazingly enough, there weren't any mosquitoes while we were there.  I'd imagine that traveling this trail right after a rain would make the entire loop a muddy slog AND filled with biting insects.
Clidemia

Edibles
As I've reviewed comments from other sites about this trail, I haven't read anything about the abundance of edibles along the way.  Besides the two types of strawberry guavas, there are also purple berries from the weed Clidemia (also known as Koster's Curse).  These prolific plants have tiny, fuzzy blueberry-like berries  a little below knee-level.  

Orange lilikoi
Orange Lilikoi: This passion fruit cousin is also known as water lemon. This plant doesn't have the three-fingered shape leaves of yellow or purple lilikoi. It isn't a prolific fruit-bearer and the fruit is rather small but it's tasty and less tart than the Yellow Lilikoi which is also found along the trail. 

Thimbleberry: This raspberry cousin is found in a few places along the trail.  The fruit is tiny but supposedly tasty.  The fruit was still white while we were there so I didn't get to sample any.

Mango: I spotted several mango trees along the trail.  I have no idea if they actually produce fruit but the potential is there.

Rose apples
Rose Apple: We found one small rose apple on the trail that had obviously fallen from it's tree.  It was tiny and not fully ripe.  These guys look a little like yellow strawberry guavas but they have a large brown seed in the middle instead of tiny guava seeds.  The fruit tastes perfume-y.

View Points
Halawa Valley and H3
There were three distinct views from the clearings.  The first lookout was of Halawa Valley with a section of the H3 freeway running through it. A bench is provided so you can sit and enjoy the view.
Kapolei area
Kapolei Area was the second scenic view.
Pearl Harbor was the third scenic view.

It was a very misty/voggy day as we hiked so my photos don't capture the beauty of the views. 

albino cricket
This was a very enjoyable trail.  We ambled along so it took us much longer than the average 2-3 hours that it takes younger people.  It was good exercise, it was interesting, and it wasn't too difficult for a recovering computer potato who spends far too much time in front of the computer.

I hope you'll enjoy the hike, too.