java - Why is this JPanel not sticking to the specified size? -
so, i'm trying learn java swing , custom components. i've created jframe, given background color, , added jpanel:
jframe frame = new jframe("testing"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(1000, 2000); frame.setbackground(color.white); jpanel jp = new jpanel(); jp.setbackground(color.blue); jp.setsize(40, 40); frame.add(jp); frame.setvisible(true);
the result 1000x2000 window colored blue (as opposed white window 40x40 blue box inside it). why jpanel expanding beyond specified size?
using code, add 1 line change layoutmanager
of jframe
. then, when add component, keep it's preferred size.
also, instead of calling jp.setsize(40,40)
, call jp.setpreferredsize(new dimension(40,40)).
and, need call pack()
on jframe
tell layout components.
jframe frame = new jframe("testing"); frame.setlayout(new flowlayout()); // new line of code frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setpreferredsize(new dimension(1000, 2000)); // modified line of code frame.setbackground(color.white); jpanel jp = new jpanel(); jp.setbackground(color.blue); jp.setpreferredsize(new dimension(40, 40)); // modified line of code frame.add(jp); frame.pack(); // added line of code frame.setvisible(true);
also, should read on of different layoutmanagers
available you. here great tutorial.
Comments
Post a Comment