Saturday, March 26, 2011

Java Applet Background Color

Problem: How do I set the background in a Java Applet?


Background: I was accustomed to treating an Applet like a JPanel. With a JPanel, you set its background color with a call to setBackground(Color). That was fine before JDK 1.6, because it was no more than a JPanel with a few differences that allow it to be rendered in a web browser. In JDK 1.6 the Applet became a top level container, which put it on the same level as the JFrame.


Solution: Since JApplet is now a top level container, I have to treat it like one.
There are two options:
Option one:
Get its ContentPane, set the background color and build your GUI on top of it.

Container cp = this.getContentPane();
Then set the ContentPane's background color:
cp.setBackground(Color.blue);
cp.add(new JLabel("Hello content pane"));

Option two:
Build your GUI on a JPanel and make it the ContentPane.

JPanel pnl = new JPanel();
pnl.add(new JLabel("Hello jpanel");
pnl.setBackground(Color.blue);
this.setContentPane(pnl);

No comments:

Post a Comment