954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

help with setting background color!!!

Hi Friends,

i made a window with a Panel and painted a text on it.
Now i want to set a background color for the panel but it does not reflect in the window..

i am posting the code here..
Please let me know if anything is wrong with the code!!

Thanks a lot!!

CODE..!!!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class MyPan extends JPanel
{
public void paintComponent(Graphics g)
{
g.drawString("Hello India",50,50);
}
}
 
class MyWin extends JFrame
{
MyWin()
{
MyPan Pan=new MyPan();
Pan.setBackground(Color.DARK_GRAY);
 
Container Con=getContentPane();
Con.add(Pan);
 
setTitle("Window With Panel");
setLocation(100,100);
setSize(300,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
 
class WinPanel
{
public static void main(String arg[])
{
MyWin w=new MyWin();
w.setVisible(true);
}
}
psodhi
Newbie Poster
11 posts since Mar 2006
Reputation Points: 10
Solved Threads: 1
 

The problem is in the paintComponent method of your MyPan class.
It should look like this:

public void paintComponent(Graphics g)
{
	super.paintComponent(g);
	g.drawString("Hello India",50,50);
}


:cheesy:

apcxpc
Junior Poster in Training
55 posts since Sep 2004
Reputation Points: 10
Solved Threads: 0
 

You should call setBackground() on the container rather than the frame.
Conn.setBackground

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

Thanks a lot apcxpc

Your advice helped me a lot..
today i read the same in a book too!!
Thanks again!!

psodhi
Newbie Poster
11 posts since Mar 2006
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You