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);         }     }  }   } 

  1. 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.

  2. use different layout manager. suspect should using gridlayout. read section swing tutorial on using layout managers more information , working examples.

  3. don't use setbounds on frame either. after add buttons frame , before invoke setvisible(..) should use frame.pack() buttons displayed @ preferred size.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -