For example, to set the application window to a border layout and to add the keypad to its east area, we would use the following statements: getContentPane().setLayout(new BorderLayout(2, 2)) The two parameters in the second version of the constructor allow you to insert spacing between the areas.Ĭomponents are added to a BorderLayout by using the add(Component, String) method found in the Container class. The BorderLayout class contains two constructors: public BorderLayout() One way to fix these problems is to use a BorderLayout to divide the frame into five areas: north, south, east, west, and center, as shown in Figure. However, despite its effort in such cases, it usually fails to achieve a completely appropriate layout. If an attempt is made to add too many components to the grid, the layout manager will try to extend the grid in some reasonable way in order to accommodate the components. If there are not enough components to fill all cells of the grid, the remaining cells are left blank. When components are added to the container, the layout manager starts inserting elements into the grid at the first cell in the first row and continues left to right across row 1, then row 2, and so on. Confusion over this point could be the source of bugs in your programs.Īs its name suggests, the GridLayout layout manager arranges components in a two-dimensional grid. The same point would apply when adding components to a JPanel: They are added directly to the panel, not to a content pane. Unlike the top-level containers, such as JFrame, other containers don’t have content panes. Note that for a JPanel, the setLayout() method applies to the panel itself. As components are added to the keypad, they will automatically be arranged by the manager into a \(4 \times 3\) grid. The higher the number, the larger the spacing. The last two arguments in the constructor affect the relative spacing between the rows and the columns. It will ensure that the keypad will have four rows and three columns of buttons (Fig. This statement creates a GridLayout object and assigns it as the layout manager for the keypad. This takes a single statement, which should be added to the beginning of the KeyPad() constructor: setLayout(new GridLayout(4,3,1,1)) Therefore, to fix this problem, we need only set the keypad’s layout to a GridLayout. A more appropriate layout for a numeric keypad would be a two-dimensional grid, which is exactly the kind of layout supplied by the. The problem was caused by the fact that as a subclass of JPanel, the KeyPad uses a default FlowLayout, which causes its buttons to be arranged in a row. It is simple to remedy the layout problem that affected the keypad in the most recent version of the Converter program. JApplet
0 Comments
Leave a Reply. |