• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

GridBagLayout Problem

 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is what im trying to achieve , which is just a sample versus on what is in the actual code. :


|-----------------------------------------------|
| Group Name :--||||textbox|||||||||||||--------|
|-----------------------------------------------|
|-----------------------------------------------|
|--Description-----Price------Quantity----------|
|-- Hotdog -----12.00------1234 ----------|
|-- Cheese -----34.56------4567 ----------|
|-----------------------------------------------|
|-----------------------------------------------|
|-- Add Button --- Remove Button ---------------|
|-----------------------------------------------|




The problem is i cant seem to show the 2 buttons below. And my mouse have to mouse over on the buttons so they will show up..

Here are the codes modified from the gridbag layout demo from Sun :

import java.awt.*;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTable;

public class ASample {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
final static String[] columnNames = {"Text Display", "Link Name","Sports","Age","Straight"};

final static Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},

{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
};




//centering the Frame
public static Point getCenteredCorner(Component c)
{
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
return new Point(
(int)((dim.getWidth() - c.getWidth()) / 2),
(int)((dim.getHeight() - c.getHeight()) / 2)
);
}






public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

JButton button;
JLabel label;
JTextField textfield;
JTable table;
JScrollPane scrollPane ;

pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
//c.fill = GridBagConstraints.NORTH;
}

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

label = new JLabel("Radio Button Group Name :");
buttonPanel.add(label);
textfield = new JTextField("",15);
buttonPanel.add(textfield);

c.weightx = 1.0;
c.gridx = 0; //col
c.gridy = 0; //row
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.insets = new Insets(10,35,100,0); //top,left,bottom,right
//c.gridwidth = 1;
c.gridheight = GridBagConstraints.REMAINDER;

pane.add(buttonPanel,c);




table = new JTable(data, columnNames);
scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(400, 100));
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
c.ipady = 150; //make this component tall
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(50,0,0,0);
//c.gridwidth = 1;
c.gridheight = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.FIRST_LINE_START;
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(scrollPane);
pane.add(buttonPanel, c);


buttonPanel = new JPanel(new FlowLayout());
button = new JButton("Add");
buttonPanel.add(button);
button = new JButton("Remove");
buttonPanel.add(button);
c.weightx = 0;
c.gridx = 0;
c.gridy = 2;
c.ipady = 0; //make this component tall
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(200,0,0,0);
//c.gridwidth = 1;
c.gridheight = GridBagConstraints.REMAINDER;
//c.anchor = GridBagConstraints.CENTER;

pane.add(buttonPanel, c);

}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {

JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.
addComponentsToPane(frame.getContentPane());

//Display the window.
frame.setSize(500,300);// width, height
//frame.setResizable(false);
frame.setLocation(getCenteredCorner(frame));

frame.pack();
frame.setVisible(true);
}

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

[ February 08, 2007: Message edited by: Cyrus Serrano ]
[ February 08, 2007: Message edited by: Cyrus Serrano ]
 
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Cyrus Serrano
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Craig, well appreciated.. thanks for the tips.. dang! this is pretty complex.. but nice to be frustrated once in a while..

Some questions on your code :

1.


//centering the Frame
public static Point getCenteredCorner(Component c) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// You can avoid the doubles by directly accessing the Dimension fields.
// This will center the JFrame in the screen.
return new Point((dim.width - c.getWidth()) / 2,
(dim.height - c.getHeight()) / 2);
}



-- what do you mean by accessing the Dimension field.. of the screen itself?, So i would not need this method anymore.. right?


2.

pack or setSize()



-- pack will compact the controls within the frame.. any differences on setSize. what i know is that setSize will just resize the window.

3. i also noticed, you did not place the components using the anchor.. how did the last jpanel (the buttons), went in the center? and you didnt use any gridx or gridy is it ok, each time i add a component. although what it seems is each time you add a component, you have implied it is the remainder of the row..

Any suggestion if i will implement several controls in a row.. will that be the time to use the gridx or gridy properties of GridBag?


Thanks
[ February 09, 2007: Message edited by: Cyrus Serrano ]
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1 — what do you mean by accessing the Dimension field.. of the screen itself?
In the original posting you had

Looking in the Dimension class api you can see that the getWidth and getHeight methods return a double. So you had to cast your width and height expressions to an int for the Point constructor. The comment was to indicate that you could avoid having to deal with the double values by not using the getWidth and getHeight methods for the Dimension dim. Looking in the Dimension class api again, see the two fields listed in the Field Summary section above the Constructor Summary section. You can access these fields directly with Dimension dim and they will return an int. So line one can be replaced by line two:

with no need to cast from double to int. The net result is a slight streamlining of your method. A small matter.

2 — -- pack will compact the controls within the frame.. any differences on setSize. what i know is that setSize will just resize the window.
We usually use one or the other of these method but not both, ie, there is usually no need to use both. Another small matter.

3 — i also noticed, you did not place the components using the anchor.. how did the last jpanel (the buttons), went in the center? and you didnt use any gridx or gridy is it ok, each time i add a component. although what it seems is each time you add a component, you have implied it is the remainder of the row..
If you look at your GridBag layout you are simply adding three JPanels to it in a single column. For this you need:
  • gridwidth == REMAINDER which will put each JPanel in a row by itself, ie, in a single column
  • weightx non–zero which will allow the JPanel to occupy more space than its preferredSize.width
  • fill == HORIZONTAL which will expand each JPanel in the horizontal to fill the parent component (Container pane, the content pane).

  • In this way of laying out the three JPanel children the anchor constraint is not needed. The FlowLayout of each JPanel handles the placement of components within the JPanel. The GridBagLayout just lays them out in single column and at the same size.
    There are many ways to work with GridBagLayout. When we are new to it we often try using the gridx and gridy constraints for placement. This works okay but can be difficult to set up properly and to debug. (In your original layout I was suspicious of the use of the gridheight constraint but did not experiment with it.) Using gridwidth is easier in that it allows you to build the children in as you go and avoids the necessity to be looking at the entire layout (constraints) for each component you add. With gridwidth you can add the components as you go and detect errors (usually) right away. This is modeled in the contents section of the GridBagLayout class api.
    Proficiency in GridBagLayout takes a lot of practice and experimenting. Seeing how others use it is helpful.
    Any suggestion if i will implement several controls in a row.. will that be the time to use the gridx or gridy properties of GridBag?
    Possibly, but not necessarily. You can add components in columns and jump to the next row with the gridwith == REMAINDER value. Sometimes, with varying gridwidth values, eg, with say 3 components in one row and more or less in another, some components will have to have a gridwith constraint value of 2 or more (and thus prevent the use of gridwidth == REMAINDER for row changing), you can move to the next row with a specific gridy value and then, after adding one or more components in the new row, reset gridy to (its default value of) RELATIVE (-1) which will allow the gridwidth to be set later (at the end of the row) to REMAINDER for row change.
     
    Cyrus Serrano
    Ranch Hand
    Posts: 137
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    hey craig.. thanks for the clarification.. hehe. i think its a matter of experiment now. hehehe
     
    machines help you to do more, but experience less. Experience this tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic