Java AWT: Setting background of Canvas changes the background for the whole frame -
why changing background color java.awt.canvas, changes background whole frame?
i set frame object follows:
public class gui extends frame { public gui() { setsize(800, 600); setlocation(0, 0); canvas cd=new canvas(); cd.setsize(500, 300); cd.setbackground(color.blue); add(cd); addwindowlistener(new windowadapter() { @override public void windowclosing(windowevent arg0) { system.exit(0); } }); } @override public void paint(graphics g) { paintcomponents(g); } public static void main(string[] args) { gui g=new gui(); g.setvisible(true); } }
the above code sets frame size 800x600, adds smaller canvas - 500x300, , sets background color color.blue
, instead of getting 500x300 blue rectangle inside bigger, 800x600 window-frame (with default grey color), result 800x600 frame blue background:
the docs says:
public void setbackground(color c)
sets background color of component.
the background color affects each component differently , parts of component affected background color may differ between operating systems.
could issue (i'm running on ubuntu)?
or missing else here?
the default layout of frame
borderlayout
(though lot of example code using awt based frame
class written in time when default layout flowlayout
). without layout constraints, component added borderlayout
end in center
constraint stretches component fits available height , width.
instead might use gridbaglayout
. when add single component gridbaglayout
without constraint, centered , size respected. e.g. (see further comments in code.)
import java.awt.*; import java.awt.event.*; public class gui extends frame { public gui() { setsize(400, 200); setlocationbyplatform(true); setlayout(new gridbaglayout()); canvas cd=new canvas(); // todo: override rather set & make preferred rather actual cd.setsize(300, 100); cd.setbackground(color.blue); add(cd); addwindowlistener(new windowadapter() { @override public void windowclosing(windowevent arg0) { system.exit(0); } }); } @override public void paint(graphics g) { //paintcomponents(g); // wrong method! super.paint(g); // right method, nothing different original! } public static void main(string[] args) { // todo: awt/swing based guis should started on edt gui g=new gui(); g.setvisible(true); } }
Comments
Post a Comment