Page 737 - Introduction to Programming with Java: A Problem Solving Approach
P. 737

                AfricanCountries Program with Labels
You might have noticed the dividing lines in Figure 17.5’s output window. Those come from the buttons’ borders, not from the BorderLayout manager. If we used label components instead of button compo- nents, you would see no dividing lines. Likewise in Figure 17.5, the margins around the words come from the button components. If we used label components instead of button components, you would see no mar- gins around the words. Below, we show what the AfricanCountries program displays when the button com- ponents are replaced with label components. Be aware that the dashed lines don’t appear on the actual window. We’ve drawn them in to show you the region boundaries.
The regions are much the same as before except that the west and east regions are narrower. That’s be-
17.4 BorderLayout Manager 703
     cause there are no margins around the words. Narrower west and east regions means there’s more room for
Apago PDF Enhancer
the center region. Thus, the center region displays its entire “Central African Republic” text.
Note that the African-country labels are left aligned. That’s the default for a label in a BorderLayout
region. If you want a different alignment than the default, instantiate the label with an alignment constant like this:
new JLabel(<label’s-text>, <alignment-constant>)
Replace <alignment-constant> by one of these named constants: SwingConstants.LEFT, Swing- Constants.CENTER, or SwingConstants.RIGHT. Here’s an example that adds a center-aligned la- bel to a BorderLayout north region:
add(new JLabel("Tunisia", SwingConstants.CENTER), BorderLayout.NORTH);
If we apply that line of code to our AfricanCountries program and we apply similar center-alignment code to our center and south regions, the program displays this:
     





















































































   735   736   737   738   739