Java Swing GridBagLayout - adding buttons without space -
how can remove spacing caused gridbaglayout , make them stick together?
here code adding 3 buttons. read question there no complete solution how fix gap in gridbaglayout;
want put of buttons on top of jframe.
import java.awt.borderlayout; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; public class myproblem { private jframe frame = new jframe(); public static void main(string[] args) { new myproblem(); } public myproblem() { frame.setlayout(new gridbaglayout()); gridbagconstraints gc = new gridbagconstraints(); gc.weightx = 1; gc.weighty = 1; gc.gridx = 0; gc.gridy = 0; gc.fill = gridbagconstraints.horizontal; gc.anchor = gridbagconstraints.north; (int = 0; < 3; i++) { jpanel jpanel = new jpanel(new borderlayout()); jpanel.setsize(80, 80); jpanel.add(new jbutton("button " + i),borderlayout.page_start); frame.add(jpanel, gc); gc.gridy++; } frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(500, 500); frame.setvisible(true); } }
how buttons like:
how want buttons like:
the layout makes single column of buttons, so..
change:
gc.fill = gridbagconstraints.horizontal;
to:
gc.fill = gridbagconstraints.both;
edit 1
i want keep buttons same height described in picture , putting them @ top.
to constrain them top easy using combined layout. in case might add panel buttons page_start
of panel borderlayout
. part of border layout stretch width of child component (our panel gridlayout
) fill available space, respect height of whatever in - giving component vertical space needs.
edit 2
here mcve implements idea described above. outer panel (with cyan colored border) used constrain height of button panel (with orange border). see comments in source more detail on how works.
import java.awt.*; import javax.swing.*; import javax.swing.border.lineborder; public class myproblem { private jframe frame = new jframe(); public static void main(string[] args) { new myproblem(); } public myproblem() { frame.setlayout(new borderlayout()); // default // use panel constrain panel buttons jpanel ui = new jpanel(new borderlayout()); frame.add(ui); ui.setborder(new lineborder(color.cyan, 3)); // panel (with gridlayout) buttons jpanel toolpanel = new jpanel(new gridlayout(0,1,0,4)); // added gap toolpanel.setborder(new lineborder(color.orange, 3)); // toolpanel appear @ top of ui panel ui.add(toolpanel, borderlayout.page_start); (int = 0; < 3; i++) { toolpanel.add(new jbutton("button " + i)); } frame.setdefaultcloseoperation(jframe.exit_on_close); //frame.setsize(500, 500); // instead.. frame.pack(); // pack make small can be. frame.setminimumsize(frame.getsize()); // nice tweak.. frame.setvisible(true); } }
Comments
Post a Comment