Fail to set Background Color
I am using Java 2 SDK 5 to develop GUI in which the background of Jframe is in black, but my program cannot change the color. Is there any wrong on my coding ? here is the piece of codes :-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class t2 extends JFrame implements ActionListener {
public t2() {
setTitle("Main Window");
setBounds(100, 100, 200, 200);
setBackground(Color.black);
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.black);
topPanel.setLayout(new BorderLayout());
JButton button = new JButton("Click Me");
button.addActionListener(this);
topPanel.add(button);
getContentPane().add(topPanel);
}
public void actionPerformed(ActionEvent event) {
new testDialog(this);
}
public static void main(String[] args) {
t2 frame = new t2();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
thanks in advance
[1057 byte] By [
cheetaha] at [2007-10-3 4:58:55]

Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags[/url] when posting code so the code is readable.
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]Using Top Level Containers[/url]. You will see that the frame is actually covered by the "Content Pane". So to change the background of the frame you really need to change the background of the content pane:
getContentPane().setBackground( Color.BLACK );
You may want to change both so you don't see a quick flicker when the frame is first painted.
The button occupies the entire space of the content pane. So of course you get the background of the button.
You can use:
button.setOpaque( false );
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html]Custom Painting[/url] for more information on how painting of components work.
thx mate, I solve the problem. I got that the reason why failed to change background color is the panel occupying the entire top layer. That's why the statement getContentPane().setBackground(Color.black) / setBackground(Color.black)
didn't affect background color. To acheive the goal, it was only to set the background color of Panel instead, like topPanel.setBackground(Color.black)
. Anyway, thx again mate you gave lots of hints.