|
I have a few JSliders to change the color and size of an Oval drawn on a JPanel.
When I Change a Color Slider it works OK and repaints the color of the Oval to the new Color. BUT when I move the circleSize slider (The left most one) When the screen is repainted the re-size of the Oval is OK andf the Color is ok but the old images have been eft behind.
How can I refresh the Panel where the circle is being resized to get rid of the old image first. How do I know when to re-paint Thanks in advance for your help.
import javax.swing.*; import javax.swing.event.*; import java.awt.*;
public class sliderCircle extends JFrame implements ChangeListener { ColorPanel canvas = new ColorPanel(); JSlider red = new JSlider(JSlider.VERTICAL, 0, 255, 255); JSlider green = new JSlider(JSlider.VERTICAL, 0, 255, 0); JSlider blue = new JSlider(JSlider.VERTICAL, 0, 255, 0); JSlider circleSize = new JSlider(JSlider.VERTICAL, 0, 50, 25);
public sliderCircle() { super("Color Slide"); setSize(350, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); //Add listeners for the different sliders
red.addChangeListener(this); green.addChangeListener(this); blue.addChangeListener(this); circleSize.addChangeListener(this); JLabel redLabel = new JLabel("R"); JLabel greenLabel = new JLabel("G"); JLabel blueLabel = new JLabel("B"); JLabel circleSizeLabel = new JLabel("Circle Size"); GridLayout grid = new GridLayout(1, 5); FlowLayout right = new FlowLayout(FlowLayout.RIGHT); Container pane = getContentPane(); pane.setLayout(grid); JPanel circleSizePanel = new JPanel(); circleSizePanel.setLayout(right); circleSizePanel.add(circleSizeLabel); circleSizePanel.add(circleSize); pane.add(circleSizePanel); JPanel redPanel = new JPanel(); redPanel.setLayout(right); redPanel.add(redLabel); redPanel.add(red); pane.add(redPanel); JPanel greenPanel = new JPanel(); greenPanel.setLayout(right); greenPanel.add(greenLabel); greenPanel.add(green); pane.add(greenPanel); JPanel bluePanel = new JPanel(); bluePanel.setLayout(right); bluePanel.add(blueLabel); bluePanel.add(blue); pane.add(bluePanel); pane.add(canvas); setContentPane(pane); }
public void stateChanged(ChangeEvent evt) { JSlider source = (JSlider)evt.getSource(); if (source.getValueIsAdjusting() != true) { Color current = new Color(red.getValue(), green.getValue(), blue.getValue()); canvas.changeColor(current); canvas.validate(); canvas.repaint(); } }
class ColorPanel extends JPanel { Color background;
ColorPanel() { background = Color.red; }
public void paintComponent(Graphics comp) { Graphics2D comp2D = (Graphics2D)comp; int radius = circleSize.getValue(); comp2D.setColor(background); comp2D.fillOval(30,30,radius,radius); }
void changeColor(Color newBackground) { background = newBackground; } }
public static void main(String[] arguments) { sliderCircle cs = new sliderCircle(); } }
|