Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

setBackgroundColor

 
Amit Lonkar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
The Backgroud color for the Panel "mp" is not getting set. Can someone tell me what change in the code is necessary.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
class MyPanel extends JPanel
{
public MyPanel()
{
super(true);
}
public void changeColor(Color c)
{
setBackground(c);
}
public void paint(Graphics g){
//super.paintComponent(g);
Line2D l = new Line2D.Double(10,10,400,400);
Graphics2D g2 = (Graphics2D)g ;
g2.setColor(Color.white);
g2.draw(l);
}
}
/*
<Applet code="Testapplet.class" width=300 height=300>
</Applet>
*/
public class Testapplet extends JApplet {
MyPanel mp;
JComboBox cb;
public void init(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mp = new MyPanel();
cb = new JComboBox();
cb.addItem("a");cb.addItem("a");cb.addItem("a");cb.addItem("a");cb.addItem("a");cb.addItem("a");cb.addItem("a");
getContentPane().add(cb, BorderLayout.NORTH);
getContentPane().add(mp, BorderLayout.CENTER);
validate();
mp.changeColor(Color.red);
}
});
}
}
Amit
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Amit,
Two things:
Since you are using Swing you should override paintComponent not paint. Therefore rename your paint routine to paintComponent.
Remove the comment delimiter from the call to the parent paintComponent method and all will work good.
Result:

Regards,
Manfred.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!