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

Not able to set the background color of JComponent

In my JApplet, I am able to change the background color of the panel but not the currentSurface which is an instance of PaintSurface extends JComponent. Could someone please help me out? Many thanks

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class Tanks extends JApplet
{
 public static final int WIDTH  = 400;
 public static final int HEIGHT = 400;
 private JButton button1;
 private PaintSurface currentSurface = new PaintSurface();
 public Tanks()
 { 
  this.add(currentSurface,BorderLayout.CENTER);
  ButtonListener b1 = new ButtonListener();
  JPanel panel = new JPanel();
  <strong>panel.setBackground(Color.white);</strong>
<strong> currentSurface.setBackground(Color.white);</strong>
  button1 = new JButton("Start");
  button1.addActionListener(b1);
  panel.add(button1);
  this.add(panel,BorderLayout.NORTH);
 }
 
 public void init()
 {
  this.setSize(WIDTH, HEIGHT);
  this.setVisible(true);
 
 }
 
 private class ButtonListener implements ActionListener
 {
 
  public void actionPerformed(ActionEvent e)
  {
   if(e.getActionCommand() == "Start")
   {
    currentSurface.figure="Start";
    repaint();
   }
  }
 
 }
}
 
class AnimationThread extends Thread
{
 JApplet c;
 public AnimationThread(JApplet c)
 {
  this.c = c;
 }
 public void run()
 {
 }
}
 
class PaintSurface extends JComponent
{
 String figure;
 
 public PaintSurface()
 {
 }
 public void paint(Graphics g)
 {
  Graphics2D g2 = (Graphics2D)g;
  g2.setRenderingHint(
   RenderingHints.KEY_ANTIALIASING,
   RenderingHints.VALUE_ANTIALIAS_ON);
 
  if(figure=="Start")
  {
   Shape s = new Ellipse2D.Float(20,50,250,150);
   g2.setPaint(Color.BLACK);
   g2.draw(s);
  }
 
 }
}
jk1998
Newbie Poster
2 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

You should be overriding paintComponent, and not paint. You also need to call setOpaque on the component.

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 
You should be overriding paintComponent, and not paint. You also need to call setOpaque on the component.



Thanks

jk1998
Newbie Poster
2 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You