Chapter 12 Graphical User Interface (Geocities web hosting) Components: Part 1
Chapter 12 Graphical User Interface Components: Part 1 699 Look-and-Feel Observation 12.11 If no region is specified when adding a Component to a BorderLayout, it is assumed that the Componentshould be added to region BorderLayout.CENTER. Common Programming Error 12.6 Adding more than one component to a particular region in a BorderLayout results in only the last component added being displayed. There is no error message to indicate this problem. When the user clicks on a particular JButton in the layout, method actionPerformed(lines 50 61) executes. The for loop at lines 52 57 uses an if/elsestructure to hide the particular JButtonthat generated the event. Method setVisible(inherited into JButton from class Component) is called with a false argument to hide the JButton. If the current JButton in the array is not the one that generated the event, method setVisibleis called with a trueargument to ensure that the JButtonis displayed on the screen. Line 60 uses LayoutManager method layoutContainer to recalculate the layout of the content pane. Notice in the screen captures of Fig. 12.25 that certain regions in the BorderLayout change shape as JButtons are hidden and displayed in other regions. Try resizing the application window to see how the various regions resize based on the width and height of the window. 12.14.3 GridLayout The GridLayoutlayout manager divides the container into a grid so that components can be placed in rows and columns. Class GridLayoutinherits directly from class Object and implements interface LayoutManager. Every Componentin a GridLayouthas the same width and height. Components are added to a GridLayout starting at the top- left cell of the grid and proceeding left-to-right until the row is full. Then the process continues left-to-right on the next row of the grid, etc. Figure 12.26 demonstrates the Grid- Layoutlayout manager using six JButtons. 1 // Fig. 12.26: GridLayoutDemo.java 2 // Demonstrating GridLayout. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class GridLayoutDemo extends JFrame 12 implements ActionListener { 13 14 private JButton buttons[]; 15 private String names[] = 16 { “one”, “two”, “three”, “four”, “five”, “six” }; 17 private boolean toggle = true; Fig. 12.26 Program that demonstrates components in GridLayout. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01