• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

setBackgroundColor

 
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
 
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.
 
This tiny ad is wafer thin:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic