java - Adding JButton by loop causes last Button to be oversized -
when create button using loop, last button has size of whole frame. how can fix this?
package test; import java.awt.*; import javax.swing.*; public class test{ private jframe frame; private static jbutton[][] buttons = new jbutton[4][4]; public static void main(string[] args) { eventqueue.invokelater(new runnable() { public void run() { try { test window = new test(); window.frame.setvisible(true); } catch (exception e) { e.printstacktrace(); } } }); } public test() { initialize(); } private void initialize() { frame = new jframe(); frame.setbounds(200, 200, 600, 600); frame.setdefaultcloseoperation(jframe.exit_on_close); for(int i=0; < 4; i++){ for(int j=0; j < 4; j++){ jbutton btn = new jbutton("" + i+j); btn.setbounds(60*i,60*j,60,60); if((i+j)%2==1) btn.setbackground(color.black); buttons[i][j] = btn; frame.add(btn); } } } }
don't use setbounds(...) on buttons. job of layout manager determine size/location of component. default layout manager jframe borderlayout. single component can added center of borderlayout, size/location of last button added being managed borderlayout , other buttons ignored.
use different layout manager. suspect should using gridlayout. read section swing tutorial on using layout managers more information , working examples.
don't use setbounds on frame either. after add buttons frame , before invoke setvisible(..) should use frame.pack() buttons displayed @ preferred size.
Comments
Post a Comment