java - Problems with GridBagLayout -
i cant transfer of relatet posts simple problem. in order gridbaglayout wrote simple example:
jframe frame = new jframe(); jpanel main =new jpanel(); frame.setcontentpane(main); gridbaglayout gbl=new gridbaglayout(); gridbagconstraints gbc = new gridbagconstraints(); main.setlayout(gbl); jbutton btn1 = new jbutton("1"); jbutton btn2 = new jbutton("2"); gbc.gridx=0; gbc.gridy=0; gbc.gridheight=1; gbc.gridwidth=1; gbc.fill=gridbagconstraints.west; gbl.setconstraints(btn1, gbc); gbc.gridx=0; gbc.gridy=1; gbl.setconstraints(btn2, gbc); frame.setsize(new dimension(200,100)); main.add(btn1); main.add(btn2); frame.setvisible(true);
here have problem neither .fill nor other parameter of gbconstrains sems work. ever 2 buttons in middle of window.
thx in advance
your configuration of gridbagconstraint
incorrect:
fill
can take:none
,vertical
,horizontal
orboth
.anchor
can use relative location within "cell"fill
,anchor
require useweightx/weighty
- try avoid using
gridx
,gridy
because hard maintain. instead use default value (relative
) , can change value ofgridwidth
/gridheight
set1
(or more if needed) ,remainder
make layout wrap next line/column (components positionned in order added container.
here working code of yours (although not sure of exact layout targetting):
import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.swingutilities; public class testgbl { protected void initui() { jframe frame = new jframe(); gridbaglayout gbl = new gridbaglayout(); jpanel main = new jpanel(gbl); frame.setcontentpane(main); gridbagconstraints gbc = new gridbagconstraints(); gbc.anchor = gridbagconstraints.west; gbc.weightx = 1.0; main.setlayout(gbl); jbutton btn1 = new jbutton("1"); jbutton btn2 = new jbutton("2"); gbl.setconstraints(btn1, gbc); gbl.setconstraints(btn2, gbc); main.add(btn1); main.add(btn2); frame.pack(); frame.setvisible(true); } public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { new testgbl().initui(); } }); } }
Comments
Post a Comment