TweetFollow Us on Twitter

Java Grids
Volume Number:12
Issue Number:11
Column Tag:Getting Started

Two Java Grid Layouts

By Dave Mark

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Last month, we introduced the Java Layout Manager and saw the power of layouts combined with panels. This month, we’ll look at two important layout classes, GridLayout and GridBagLayout, and present a series of applets that bring these two classes to life.

There is a newly reformatted set of Java API documentation, collectively known as the 1.0.2 API. If you don’t already have this, go get it now. The URL is:

http://java.sun.com/doc/api_documentation.html

There are two Mac download links on this page. Though it’s bigger, you might try the .hqx file (as opposed to the .bin file). I’m not sure why, but when I downloaded the .bin file and dropped it on StuffIt Expander, the final .sea file was corrupted. On the other hand, by the time you read this, the problem most likely will have been corrected.

GridLayout

As its name implies, the GridLayout lays out its components in a grid. GridLayout has two constructors:

public GridLayout( int  rows, int  cols );

This one creates a grid layout with the specified rows and columns. As you’ll see, GridLayout does the best it can to lay the current set of components out in this configuration. But what if you have too few components? Or too many? This month’s sample applets are ideal for experimenting.

The second constructor adds two new parameters:

public GridLayout( int  rows, int  cols,
                   int  hgap, int  vgap );

This version creates a grid layout with the specified rows and columns, but also lets you specify a minimal horizontal and vertical gap to appear between the components.

GridLayout is pretty straightforward. Here’s a sample applet to take it for a spin.

• Launch the CodeWarrior IDE and create a new “Java Applet” project called GridLayout.µ.

• Create a new source code window, type in the following source code, save as GridLayout.Java, and add to it the project.

import java.awt.*;

public class MyGrid extends java.applet.Applet
{
 public MyGrid()
 {
 setLayout( new GridLayout( 4, 4 ) );
 
 add( new Button( “1” ) );
 add( new Button( “2” ) );
 add( new Button( “3” ) );
 add( new Button( “4” ) );
 add( new Button( “5” ) );
 add( new Button( “6” ) );
 add( new Button( “7” ) );
 add( new Button( “8” ) );
 add( new Button( “9” ) );
 add( new Button( “10” ) );
 add( new Button( “11” ) );
 add( new Button( “12” ) );
 add( new Button( “13” ) );
 add( new Button( “14” ) );
 add( new Button( “15” ) );
 add( new Button( “16” ) );
 }
}

• Create a second source code window, type in the following HTML, save as GridLayout.html, and add it to the project as well.

<title>GridLayout</title>
<hr>
<applet codebase=”GridLayout Files” code=”MyGrid.class” width=200 height=200>
</applet>
<hr>
<a href=”GridLayout.java”>The source.</a>

• Remove the two <replace me> files from the project (Apple-click on the files to select them, then hit option-delete).

• Edit the project prefs, specifically, the Java Project pane. Set the Project Type popup to “Class Folder” and type “GridLayout Files” (without the quotes) as the Folder Name.

It’s important that the Class Folder preference exactly match the “codebase” attribute in your HTML file.

• Once all your source is in place, select Make from the Project menu to generate your class file.

• To run your applet, drop the html file onto your Java Applet runner or Java-capable browser. Figure 1 shows my version running in a Netscape window.

Figure 1. The GridLayout applet, running in Netscape.

The GridLayout Source Code

Here’s how the source code works. First comes the normal opening stuff, the import statement and class definition. The setLayout() statement creates a new GridLayout object with 4 rows and 4 columns, and makes it the current layout.

import java.awt.*;

public class MyGrid extends java.applet.Applet
{
 public MyGrid()
 {
 setLayout( new GridLayout( 4, 4 ) );

Next, we create a series of 16 buttons and add them to the current frame.

 add( new Button( “1” ) );
 add( new Button( “2” ) );
 add( new Button( “3” ) );
 add( new Button( “4” ) );
 add( new Button( “5” ) );
 add( new Button( “6” ) );
 add( new Button( “7” ) );
 add( new Button( “8” ) );
 add( new Button( “9” ) );
 add( new Button( “10” ) );
 add( new Button( “11” ) );
 add( new Button( “12” ) );
 add( new Button( “13” ) );
 add( new Button( “14” ) );
 add( new Button( “15” ) );
 add( new Button( “16” ) );
 }
}

That’s it! When you run the applet, your 16 buttons will appear in a 4 by 4 grid. The width and height of the buttons is determined by the width and height attributes in your HTML’s applet tag. Make the applet frame wider, the buttons will each be made wider. Make the frame taller, the buttons will each be made taller.

You can also affect the results by changing the parameters you pass to the GridLayout constructor. Experiment.

GridLayout, Version 2

Here’s another GridLayout applet. This one uses all four constructor parameters, and includes a nifty little trick you’ll want to remember. First, here’s the code:

import java.awt.*;

public class MyGrid extends java.applet.Applet
{
 int    numButtons;
 String att;
 
 public void init()
 {
 att = getParameter( “NUMBUTTONS” );
 numButtons = Integer.valueOf(att).intValue();
 
 setLayout( new GridLayout( 2, 20, 5, 20 ) );
 
 for ( int i=1; i<=numButtons; i++ )
 add( new Button( “”+i ) );
 }
}

Next, here’s the HTML:

<title>GridLayout</title>
<hr>
<applet codebase=”GridLayout Files” code=”MyGrid.class” width=400 height=200>
<param name=”NUMBUTTONS” value=”16”>
</applet>
<hr>
<a href=”GridLayout.java”>The source.</a>

Figure 2 shows the applet in action, running under Netscape. Let’s take a look at this source.

Figure 2. Another GridLayout applet using all 4 parameters.

GridLayout 2 Source Code

This version of GridLayout.Java starts off in the same way, but does its creating in init() instead of in MyGrid(). This gives us access to the HTML parameters. I’m not sure why getParameter() doesn’t work from within MyGrid(), but I’ll look into it.

import java.awt.*;

public class MyGrid extends java.applet.Applet
{
 int    numButtons;
 String att;

If you look back at the HTML, you’ll see that we stuck in a parameter with the name “NUMBUTTONS” and a value of “16”. We call getParameter() to pick up the parameter and Integer.valueOf(att).intValue() to convert the returned string to a number. Next, we create a new GridLayout using all 4 parameters and make it the current layout. Note that we’ve specified 2 rows and 20 columns, with 5 pixels horizontally and 20 pixels vertically between components. The Layout Manager uses the row value first for GridLayouts, so the fact that you’ve specified 20 columns really has no affect. Try using 0 for a column value.

 public void init()
 {
 att = getParameter( “NUMBUTTONS” );
 numButtons = Integer.valueOf(att).intValue();
 
 setLayout( new GridLayout( 2, 20, 5, 20 ) );

Now for the cool trick. In our earlier example, we explicitly specified the name of each button using Strings like “1”, “2”, etc. In this case, we add the loop counter, i, to the null string to produce a string representation of the loop counter. Basically, we’ve forced Java to do the typecasting from number to String for us, since the + operator is expecting a String on both sides. Pretty cool, eh?

 for ( int i=1; i<=numButtons; i++ )
 add( new Button( “”+i ) );
 }
}

The GridBagLayout

The GridLayout works pretty well if all your components are the same size. But, suppose you are working with all sorts of elements; some tall, some wide, whatever. In this case, the GridLayout won’t work particularly well (it’ll waste a lot of screen real estate). Fortunately, there is a complex, grid-based class designed to handle variable sized components.

GridBagLayout and its sister class, GridBagConstraints, allow you to customize a layout that allows components to span multiple grid cells. The GridBagConstraints class features a number of variables, each designed to constrain any components added to the current GridBagLayout. Take a look at the GridBagConstraints class declaration:

public  class  Java.awt.GridBagConstraints
    extends  Java.lang.Object
    implements Java.lang.Cloneable
{
        // Fields
    public int anchor;
    public int fill;
    public int gridheight;
    public int gridwidth;
    public int gridx;
    public int gridy;
    public Insets insets;
    public int ipadx;
    public int ipady;
    public double weightx;
    public double weighty;

        // the anchor field has one of the following values     
    public final static int CENTER;
    public final static int EAST;
    public final static int NORTH;
    public final static int NORTHEAST;
    public final static int NORTHWEST;
    public final static int SOUTH;
    public final static int SOUTHEAST;
    public final static int SOUTHWEST;
    public final static int WEST;

        // the fill field has one of the following values       
    public final static int BOTH;
    public final static int HORIZONTAL;
    public final static int NONE;
    public final static int VERTICAL;

        // default value for gridheight, gridwidth
    public final static int REMAINDER;

        // default value for gridx, gridy
    public final static int RELATIVE;

        // Constructors
    public GridBagConstraints();

        // Methods
    public Object clone();
}

To use a GridBagLayout, you’ll create a GridBagLayout object along with a corresponding GridBagConstraints object, then make the GridBagLayout the current object. Next, you’ll set your GridBagConstraints fields to the settings you prefer. Now you are ready to start adding components to the current frame. All the added components will be formatted according to the current GridBagConstraints settings. Change the constraints settings and add some more components. The changed constraints only affect future components, not the components that were already added.

anchor determines where, within a cell, the component is placed. fill determines if the component is reissued to fill its cell and, if so, how. gridheight specifies the number of cells in a column. gridwidth specifies the number of cells in a row. REMAINDER is used to mark a component as the last in its row or column. RELATIVE is used to mark a component as next to last.

gridx and gridy allow you to specify where to place the component in the grid. A value of (0,0) will put the next component in the upper left corner. A value of RELATIVE will put the component either at the end of a row (in the case of gridx) or column (in the case of gridy).

insets specifies the number of pixels of padding on any side of a cell. ipadx and ipady allow you to specify the padding in pixels within a cell.

Finally, weightx and weighty allow you to specify how much horizontal and vertical space this component should consume when the available extra display area is divvied up between all the components in a row or column.

A GridBagLayout Example

There is really no way to truly appreciate the GridBagLayout without playing with an example. The following is one of the standard Sun applets, stripped down to make it as small as possible. Take some time to play with this applet. Change the constraints, experiment with all the fields and settings to see what they do.

Here’s the source code:

import java.awt.*;

public class MyGridBag extends java.applet.Applet
{
 public MyGridBag()
 {
 GridBagLayout   gridBag = new GridBagLayout();
 GridBagConstraintsconstraints =
                new GridBagConstraints();
 
 setLayout( gridBag );
 
 constraints.fill  =  constraints.BOTH;
 constraints.weightx  =  1.0;

 ConstrainedButton(“Button1”,  gridBag,  constraints );
 ConstrainedButton(“Button2”,  gridBag,  constraints );
 ConstrainedButton(“Button3”,  gridBag,  constraints );

 constraints.gridwidth  =  constraints.REMAINDER;  

 ConstrainedButton(“Button4”,  gridBag,  constraints );

 constraints.weightx  =  0.0;

 ConstrainedButton(“Button5”,  gridBag,  constraints );
 
 constraints.gridwidth  =  constraints.RELATIVE;
 
 ConstrainedButton(“Button6”,  gridBag,  constraints );
 
 constraints.gridwidth  =  constraints.REMAINDER;
 
 ConstrainedButton(“Button7”,  gridBag,  constraints );
 
 constraints.gridwidth  =  1;
 constraints.gridheight  =  2;
 constraints.weighty  =  1.0;
 
 ConstrainedButton(“Button8”,  gridBag,  constraints );
 
 constraints.weighty  =  0.0;
 constraints.gridwidth  =  constraints.REMAINDER;  
 constraints.gridheight  =  1;
 
 ConstrainedButton(“Button9”,  gridBag,  constraints );
 ConstrainedButton(“Button10”,  gridBag,  constraints );
 }
 
 void ConstrainedButton( String title,
 GridBagLayout layout, GridBagConstraints constraints )
 {
 Button button = new Button( title );
 layout.setConstraints( button, constraints );
 add( button );
 }
}

Here’s the HTML:

<title>GridBagLayout</title>
<hr>
<applet codebase=”GridBagLayout Files” code=”MyGridBag.class” width=400 
height=100>
</applet>
<hr>
<a href=”GridBagLayout.java”>The source.</a>

Figure 3 shows the results of this applet, when run in Netscape.

Figure 3. The classic GridBagLayout applet from Sun.

Till Next Month...

As you go through the GridBagLayout source, pay attention to the use of REMAINDER and RELATIVE. Remember, you are marking a component as 2nd to last and last in its row or column. For example, Button4 should be the last in its row. Button6 should be RELATIVE (2nd to last) while Button7 should be REMAINDER (last). All the buttons should use a gridheight of 1 except for Button8, which will use a gridheight of 2. You get the idea.

Next month, we’ll take a look at double-buffered animation, something that Java makes fairly easy to do. Till then, have a Happy Thanksgiving and save me a wishbone...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

*Apple* Software Developer - TEKsystems (Uni...
Description: The Kentucky State Board of Elections is seeking a contractor-based Apple Software developer to create and maintain an iPad based software application Read more
W10 & *Apple* Desktop Support - TEKsyst...
…where in that experience range 6 months to 3 years) W7/10 Apple OSX OS Support and general Client Networking support Desktop/Laptop Installation/de-installation Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.