java - Cant get JLabels allign properly -
i have list of categories , each category has image, need display images 1 after other (4 @ row) spaces between them. have problem displaying last label, seems setbounds method doesn't affect it. created jpanel , add labels containing images panel. source code, added link screenshot
thanks!
jframe frame = new jframe("test"); jpanel panel = new jpanel(); panel.setbackground(color.white); java.util.iterator<entry<integer, y2category>> = configfile.categories.entryset().iterator(); int positionx = 50; int positiony = 50; int linecounter = 0; while( it.hasnext() ) { map.entry<integer, y2category> pairs = (entry<integer, y2category>) it.next(); y2category cat = (y2category) pairs.getvalue(); jlabel label = new jlabel( new imageicon( "img\\main\\black.png" ), jlabel.center ); label.setbounds(positionx,positiony,115,179); label.setfont(new font("arial", font.plain, 14)); panel.add(label); positionx += 220; linecounter++; if ( linecounter == 4 ) { linecounter = 0; positiony += 200; positionx = 50; } } frame.add(panel); //imageicon icon = new imageicon("img\\icon.jpg"); //frame.seticonimage(icon.getimage()); frame.setresizable( false ); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(900,900); dimension dim = toolkit.getdefaulttoolkit().getscreensize(); frame.setlocation(dim.width/2-frame.getsize().width/2, dim.height/2-frame.getsize().height/2); frame.setvisible(true);
using null layout never recommendable. setbounds() method sets location static , unsuitable dynamic ui. when need add component in between @ later stage need update of code i.e. modify setbounds() of effected components.
i recommend using gridbaglayout flexible , need set grid components. have written small sample code understand:
public jpanel getcomponentpanel() { if(null == componentpanel) { componentpanel = new jpanel(); gridbaglayout gridbaglayout = new gridbaglayout(); componentpanel.setlayout(gridbaglayout); // create single constraint reused gridbagconstraints constraint = new gridbagconstraints(); // insets provide spacing in format (top, left, bottom, right) constraint.insets = new insets(10, 10, 10, 10); // gridx x-axis positioning , gridy y-axis positioning constraint.gridx = 0; constraint.gridy = 0; label1 = new jlabel("label 1"); componentpanel.add(label1, constraint); constraint.gridx = 1; constraint.gridy = 0; label2 = new jlabel("label 2"); componentpanel.add(label2, constraint); constraint.gridx = 2; constraint.gridy = 0; label3 = new jlabel("label 3"); componentpanel.add(label3, constraint); constraint.gridx = 3; constraint.gridy = 0; label4 = new jlabel("label 4"); componentpanel.add(label4, constraint); constraint.gridx = 0; constraint.gridy = 1; label5 = new jlabel("label 5"); componentpanel.add(label5, constraint); . . . . constraint.gridx = 3; constraint.gridy = 3; labelxyz = new jlabel("label 5"); componentpanel.add(labelxyz, constraint); } return componentpanel; }
Comments
Post a Comment