Java Move to new row if all columns filled grid -
i trying make list of buttons created dynamically. arranging them using gridlayout. want that, if buttons number exceeds particular number 12, row must change i.e. in every row there 12 buttons.
string[] linesarray = lines.toarray(new string[datacount]); setlayout(new java.awt.gridlayout(4, 4)); (int = 0; < datacount; i++) { gridbagconstraints c = new gridbagconstraints(); jpanel1.setlayout(new gridbaglayout()); c.fill = gridbagconstraints.horizontal; c.weightx = 0; //c.weighty = 1; c.gridx = 0; if(i > 12) c.gridy = 1; buttons[i] = new jbutton(linesarray[i]); buttons[i].setname("iname"+i); buttons[i].setpreferredsize(new dimension(100, 80)); jpanel1.add(buttons[i], c); jpanel1.setbackground(color.white); jpanel1.setborder(borderfactory.creatematteborder(0,0,1,0,color.black)); } how can achieve above task ?
it seems know in advance how many buttons you're going create, since you're looping on datacount variable , creating new button in each iteration.
now you're creating grid layout following constructor:
new java.awt.gridlayout(rows, cols) and you're creating 4x4. when create it, check see how many columns want create. example:
int cols = datacount > 12 ? datacount / 12 : datacount / 4; int rows = (int)math.ceil(datacount / cols); setlayout(new java.awt.gridlayout(rows, cols)); you might want check fine tuning of math.ceil ensure enough rows , columns contain data.
hope helps.
Comments
Post a Comment