Chapter 7

Test Your Thinking

In creating Figure 7.12, we reused the same set of GridBagConstraints for each button.  We could just as easily have created a new GridBagConstraints object for each button, and then set each component's values separately. 

1) What are the pros and cons of these two approaches?

 

Answer:

This is a bit subjective, so here are the authors' take on the matter:

Pros of reusing GridBagConstraints:

·         Old values passed on to next component.  If you are going to be setting the same values for all or most of your components, then reusing the same constraints object is helpful because you don't have to keep resetting the attribute values from their default values.

·         If you need to change a setting for all components, you just change it in one place and the value "trickles" down to the rest.

·         Makes code shorter (helpful when writing books!).

·         Makes code a miniscule amount faster.

Cons of reusing GridBagConstraints:

·         Old values passed on to next component.  This "pro" can also be a "con."  Some times a setting you don't want set is passed to a component.

·         Makes code easier to read and understand, as it can be hard to keep track of which settings are set.

·         Makes code easier to debug.  Since you have to set each constraint attribute for each component, it's usually easy to see what each value is.

So, what's the final choice?  It's up to you and what you're comfortable with.  For beginners, it might be wiser to use a new GridBagConstraints for each component, but after you're comfortable with them, you might find it more efficient to reuse the same one.

 


 

2) Create a layout that draws a numeric keypad like the one found on a standard computer keyboard.

 

Answer: You already have an example in the book that uses just GridLayout and BorderLayout.  Here is a second example that uses the GridBagLayout manager.

 

Again, this isn't perfect, but it maintains the proportions of a real numeric keypad much better than the example in the book does.  It's also an applet, so you can (hopefully) view it from this web page.

 

Click here for the NumPadApplet source code.

 

Click here for the NumPadApplet.

 


 

3) Simulate a BorderLayout using a GridLayout.

 

Answer:

Did we say GridLayout?  Uh, we actually meant to say GridBagLayout.  Unfortunately, we missed that little fact in all our proofreading (it was spelled correctly!)

 

The key here is to have the north component behave as if it were in the NORTH of a BorderLayout.  The same would go for the south, east, west, and center components.

 

Click here for the SimulatedBorderLayout source code.

 

 Click here for the SimulatedBorderLayout applet.

 

We created the "West" button with longer text to show that the West region (as well as East) will only be as wide as the component itself.  We used the weightx and weighty constraints to control the sizing of each region.