wood burning stoves 2.0*
The moose likes Swing / AWT / SWT and the fly likes GridBagLayout and JFrame Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "GridBagLayout and JFrame" Watch "GridBagLayout and JFrame" New topic
Author

GridBagLayout and JFrame

Howard Pepper
Greenhorn

Joined: Mar 06, 2006
Posts: 5
Hello all, I recently started back relearning my Java (I worked in it extensively from late 1997 through mid 2001), and picked the Sun Java tutorials to work with.

After going through (hand-typing in) about a dozen or so of the applications (mainly the Swing path), I decided to reinforce my learning by creating my own application. I wanted to create a small, simple calculator application, and managed to get the UI fleshed-out yesterday. I am extendign a JFrame and changing the layout manager to GridBagLayout. The application displays fine, but when I try to resize it (expand it), the frame will expand, but the internal calculator stays the same size. I have tried putting this on a JPanel and then adding the JPanel to the JFrame, I've tried using the JPanel and replacing the content pane of the JFrame with the JPanel component, but they all fail for the same thing: no resize of the calculator.

I don't want to put the entire source listing on here, because it is about 116 lines long, but here are some of the sections (some of the start-up code at the bottom is from the Java turorials):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class jSimpleCalc2 extends JFrame implements ActionListener {
......
public jSimpleCalc2() {
initializeGUI();
}

/**
* Set up the calculator UI.
*/
protected void initializeGUI() {
if(RIGHT_TO_LEFT) {
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if(shouldFill) {
// Maximum height, maximum width
c.fill = GridBagConstraints.BOTH;
}
c.ipadx = 2;
c.ipady = 2;
c.insets = new Insets(1, 1, 1, 1);

calcDisplay = new JLabel(calcValue);
calcDisplay.setHorizontalAlignment(JLabel.RIGHT);
calcDisplay.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));

c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
add(calcDisplay, c);

pack();
setVisible(true);
.....
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

// Create and set up the content pane.
jSimpleCalc2 myCalc = new jSimpleCalc2();
myCalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
// Schedue a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Any help would be appreciated. It will work the way it is, if I set the frame's setResizable() method to false, but I want to be able to resize it.

TIA,
Howard
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I feel your pain - GridBagLayout isn't fun to work with (see http://madbean.com/anim/totallygridbag )

I would avoid using GridBagLayout wherever possible. Often it is possible (and simpler in the long run) to nest other LayoutManagers to get the same result.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Howard Pepper
Greenhorn

Joined: Mar 06, 2006
Posts: 5
Ilja,

Heheheh. That was very funny! Trouble is, I'm trying to get the GridBagLayout to work. Actually, the UI looks excellent Here's a screenshot of it:



The problem is, it won't resize at all! You can not shrink the frame (which is what I wanted, the size shown is the minimum size), but when you try to grow it, here's what happens:



I know I could use another layout manager, but I really want to get this working. Any help provided would be greatly appreciated!

TIA,
Howard
Howard Pepper
Greenhorn

Joined: Mar 06, 2006
Posts: 5
Eureka! I've got it!!! :-)

If you want the GridBagLayout to expand as you expand the frame, you have to set the GridBagConstraints.weightx and GridBagConstraints.weighty to 1.0. If you set them to 0.0, the GridBagLayout will not expand!!!

I added the line:

c.weightx = c.weighty = 1.0

below the line where I set the fill, and it works as advertised!

See, the GridBagLayout isn't all that difficult. You just have to judiciously use Google! ;-)

Regards,
Howard
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Nice to see that you made it work!

Personally, I wouldn't call it intuitive, but to each his own...
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
Well done but I would tend to agree with Ilja Preuss.

We can use JPanels in combination with different SWING layout managers to achieve the same results and save lot of pain. If you still need to use a GridBagLayout then one can use a GridBagLayout tool which helps you revrse engineer your lokk and feel to JAVA code:

GridBagger Tool
[ March 07, 2006: Message edited by: ak pillai ]

java j2ee job interview questions with answers | Learn the core concepts and the key areas
Howard Pepper
Greenhorn

Joined: Mar 06, 2006
Posts: 5
Thanks for all the help and information folks. I really appreciate it.

With this small application, the focus was on learning how to use the GridBagLayout layout. Although I could have switched to different layout managers and multiple panes, it would have defeated the purpose of writing the app.

What did I learn from this? Well, I learned that the GridBagLayout is very complex and full of little twists and turns, but it can be used effectively, with a bit of reading. I think my main problem with the layout was the documentation from Sun. At no point in the documentation for GridBagLayout or GridBagConstraints did it specify you needed to set weightx and weighty > 0 in order to resize the panel. That would have solved my problem before it became a problem.

In searching for information on the GridBagLayout, I found more than anything else, people advising you not to use it, to try something else. I also checked my mighty tome of wisdom from O'Reilly, "Developing GUIs in Java, Java Swing", and the only mention it gives to the GridBagLayout is that while you could use it, you would be better served by using the SpringLayout. I think the GridBagLayout has received so much "bad press" from developers that no one wishes to use it any more, and new Java developers aren't even learning how to use it. That's too bad, because it does still hold a viable position in a developer's tool box.

By the way, should anyone care, the actual code to produce the calculator UI takes up surprisingly little room (the application was completely hand-coded). In fact, the majority of the UI code is in the two-dimensional array that is used to generate the buttons. The actual setup of the GridBagConstraints is fairly simple.

Again, thank you all.

Howard
Martin Simons
Ranch Hand

Joined: Mar 02, 2006
Posts: 196
Actually it does. Here from the API doc:

GridBagConstraints.weightx, GridBagConstraints.weighty
Used to determine how to distribute space, which is important for specifying resizing behavior. Unless you specify a weight for at least one component in a row (weightx) and column (weighty), all the components clump together in the center of their container. This is because when the weight is zero (the default), the GridBagLayout object puts any extra space between its grid of cells and the edges of the container.
Sam Codean
Ranch Hand

Joined: Feb 26, 2006
Posts: 194
A good thread of mails!!
I am an ardent fan of the GridBagLayout so maybe i will not have many supporters
I like the flexibility that the LAyout provides and i think a little practise on this layout will definitely make people realize the usefulness of the same. But finally yes it is upon the person to use his preferred layout.
As far as it works and works WELL, it is a good code.


-Sam Codean<br />SCJP 1.4 (98%)<br />SCJD 5.0 (87.5%)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I'm not saying that GridBagLayout is not powerful, or cannot be understood.

What I'm saying is that code using GridBagLayout is harder to understand than it needs to be. There simply are alternatives available that are as powerful, but much easier to use, so I don't know why I should accept the pain to use GBL.
 
 
subject: GridBagLayout and JFrame