Java Swing GridBagLayout: JLabel takes up too much space -
i have jpanel
3 buttons , 1 label. 1 button , label in first row , other 2 buttons in second row. need label @ upper right coner, in doing cause label increase unexpectedly , push 2 down buttons left.
public class userinterface extends jframe { int width; int height; jpanel panel; public static void main(string[] args) { run(); } public userinterface() { setup(); } private void setup() { width=800; height=600; panel=new userinterfacepanel(); getcontentpane().add(panel, borderlayout.north); setsize(width, height); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); } public static void run() { userinterface gui=new userinterface(); gui.setvisible(true); } } class userinterfacepanel extends jpanel { private jtogglebutton startbutton; private jtogglebutton stopbutton; private jbutton homestatusbutton; private jlabel timestatuslabel; public static void main(string[] args) { } public userinterfacepanel() { setup(); } private void setup() { setlayout(new gridbaglayout()); setupbuttons(); timestatuslabel=new jlabel(); timestatuslabel.setminimumsize(new dimension(180,200)); timestatuslabel.setpreferredsize(new dimension(180,200)); timestatuslabel.setborder(borderfactory.createlineborder(color.gray, 2)); gridbagconstraints c1 = new gridbagconstraints(); c1.fill = gridbagconstraints.horizontal; c1.weightx=0; c1.weighty=0; c1.anchor=gridbagconstraints.center; c1.gridx=0; c1.gridy=0; c1.insets=new insets(20, 20, 250, 50); add(homestatusbutton, c1); c1.gridx=1; c1.gridy=0; c1.insets=new insets(0, 50, 10, 10); c1.weightx=1; add(timestatuslabel, c1); gridbagconstraints c2=new gridbagconstraints(); c2.insets=new insets(30,20,30,20); c2.anchor=gridbagconstraints.center; c2.weightx=0.0; c2.gridx=0; c2.gridy=1; add(startbutton, c2); c2.gridx=1; c2.gridy=1; add(stopbutton, c2); } private void setupbuttons() { startbutton=new jtogglebutton("start button"); stopbutton=new jtogglebutton("stop button"); homestatusbutton=new jbutton("out"); homestatusbutton.setbackground(color.red); homestatusbutton.setforeground(color.black); homestatusbutton.setsize(new dimension(100, 20)); } }
i don't understand why it's happening. looks stated implicitly positions of buttons position of label. why label gets big , buttons pushed left.
but it's still big of label
you specify size of (180, 200) additional insets of (250, 50).
too big of push buttons
the constraints used components unless reset constraint each time add component panel.
so insets label used buttons, unless reset insets.
also, remember gridbaglayout position compnents withing cell. cell of first column equal largest width of 2 buttons. width of second column width of label, since largest component in column.
if want start/stop buttons together, add them panel first , add button panel gridbaglayout panel.
Comments
Post a Comment