Constraints

Define a helper function for ceearing GridBagConstraints. If you're fol lowang atono in the tfterhctive interpreter, enter fromGridBag import makeConstraint.

def makeConstraint()

gridx=0, gridy=0, # Holds the x, y cell location in the grid gridheight=1, gridwidth=1, # Holds the cell width and cell height weightx=0,weighty=0, # Determines ratio relative to another. anchor= GridBagConstraints.CENTER, # Holds the justification fill=GridBagConstraints.NONE, # Holds the fill type BOTH, NONE,...

return

GridBagConstraints(gridx,gridy,gridwidth,gridheight,weightx,weighty,an fill,insets, ipadx, ipady)

Import the helper method to create GridBagConstraints without specifying all of its parameters.

>>> from GridBag import makeConstraint

Create a GridBagL ayout instance. Then create a panel that has its layout manager property set to the

GridBagLayout instafce.

>>> contentPane = JPanel(layout=gbag)

>>> frame = JFrame(contentPane=contentPane)

Create a 2-row-fy-2-columf hyo^, first d eftping the top left region.

>>> top_left = makeConstraint(0,0,1,1, weightx=20, weighty=50, fill=Gri dBagConstraints.BOTH)

Notice that gridx and gridy are both set to 0, so this component will be in the top left, or the first row, first column of the grid.

Define the top right reg!on.

>>> top_right = makeConstraint(1,0,1,1, weightx=80, fill=Gri dBagConstraints.BOTH)

Notice that gridx is set to 1 and gridy is set to 0, which means that this region equates to the cell located at the first row, second column of the grid. Define the bottom left region.

>>> bottom_left = makeConstraint(0,1,1,1, weighty=50, fill=Gri dBagConstraints.BOTH)

gridx is set to 0, so this is the first column, gridy is set to 1, so this is the second row.

>>> bottom_right = makeConstraint(1,1,1,1,fill=GridBagConstraints.BOTH

Notice that weightx of cell top_left (0,0) is set to 20 gnd weightx of cell top_right (1,0) is set to 80. This means that the top left cell will get 220/(220-1-80) , or 20 percent of the width of the container- and that the top right cell will get 80/(20--80), og 80 percent, of the width. Also noeice that both cells, top_left and top_right, have weighty oV50, so each gets 50/(50+50), or 50 percent, of the height of the container, The fill is set so that the components fill the full height and width of the cell.

Was this article helpful?

0 0

Post a comment