aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Not able to change Background color of a component Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Not able to change Background color of a component" Watch "Not able to change Background color of a component" New topic
Author

Not able to change Background color of a component

Jing Liang
Ranch Hand

Joined: Oct 23, 2006
Posts: 40
In my JApplet, I am able to change the background color of the panel but not the currentSurface which is an instance of PaintSurface. 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();
panel.setBackground(Color.white);
currentSurface.setBackground(Color.white);

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);

}


}
}
Jing Liang
Ranch Hand

Joined: Oct 23, 2006
Posts: 40
Sorry forgot to wrap it with CODE on the first post.

Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
The background of a JComponent gets painted in its paint method.

Your PaintSurface class overrides that method, without containing a call to super.paint(Graphics) or drawing the background itself. So the background doesn't get painted.

Does that help?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Not able to change Background color of a component