Change color randomly of object

Hi,
I wrote a small application simulating a road traffic. I am using threads to do the animation.
this is the code:
public class TestProject extends Frame implements Runnable
   public static int frame;   // int variable for frame (animation)
    int delay = 100;    // delay for animation
    Thread animator, light;    // thread name
     * Create a thread and start it.
    public void start()
        animator = new Thread(this);    // create new thread
        animator.start();               // start thread
     * This method is called by the thread that was created in
     * the start method. It does the main animation.
    public void run()
        // Remember the starting time
        long tm = System.currentTimeMillis();   // get time (ms) and store it in tm
        while (Thread.currentThread() == animator)
            // Display the next frame of animation.
            if (frame==(200*roadArrangement.size()+50)) // if object reaches "end" reset
                frame =-50; // "reset" frame
            repaint();  // repaint object
            // Delay depending on how far we are behind.
            try
                tm += delay;    // delay
                Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
            catch (InterruptedException e) // catch exception for thread
                System.out.println("error in thread interrupt!");
                break;
            frame++;    // Advance the frame
    } // end of run
     * Set the animator variable to null so that the
     * thread will exit before displaying the next frame.
    public void stop()
        animator = null;
     * Paint a frame of animation.
    public void paint(Graphics g)
        for(int i = 0; i < roadArrangement.size(); i++)
            String tempType = roadArrangement.elementAt(i).toString();
            char roadType = tempType.charAt(0);
            g.setColor(Color.darkGray);
            if(roadType == 'r')
                g.setColor(Color.darkGray);
                g.fill3DRect(10+(i*210),100,210,60,true);
            else if(roadType == 'j')
                g.setColor(Color.darkGray);
                g.fill3DRect(10+(i*210),100,210,60,true);
                g.fill3DRect(85+(i*210),160,60,70,true);
                g.fill3DRect(85+(i*210),30,60,70,true);
                g.setColor(Color.green); // traffic light color
                g.fillOval(10+(i*210)+50,30+100,10,10); // traffic light
                Color clr = g.getColor();
                int red = clr.getRed();
                if((frame == (10+(i*210)+50))&&(red==255))
                    stop(); // stop thread to stop cars
                    System.out.println("STOP");  
}In the code I have "oval" traffic lights where I set the colours.
Now, what I want to do is that traffic lights change independently and randomly their colour so that cars stop and drive.
How can I do this? Will I need a second thread? If yes, how to implement that?
thanks in advance.

Use [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html]Random class and call nextInt every time in paint method than match a color to the int you get back.

Similar Messages

  • Why the lookandfeel change color randomly?

    why the lookandfeel change color randomly?
    after my API moves JDK1.4 to 1.5, the problem appeared.
    the Max/Min/Close button of JFrame also change to other style.

    yes, I have reset the Theme of MetalLookAndFeel.setCurrentTheme() to myself, but sometime it looks useless. It will use oceanTheme or myTheme randomly.
    Then I add a loop to check the current theme till it use mytheme.
    The new problem the min/max/close button changed randomly, though that is much less frequent.

  • Can I change color of all objects at ones ?

    Hello guys
    I understand that's very fundamental question, and I promise I search the forum prior to posting, but perhaps it's my bad english and wrong phrasing, that leads to poor results. So if that has been discuss, please kindly don't waste your time, just link me to the post and I will read away.
    I have very complex file, with hundreds of paths, shapes, text, outlined text,  etc... It's a brochure with graphs, scematich drawings and text.
    Last moment, the client like the reverse the colors from (current) Black on white, to all White on dark gray background.
    Problem is, I can't seem to find easy way to just change the colors, without selecting one by one, every single object. When I selest all and choose white, it start filling paths with solid fill... Editing it wastes allot of my time and I have many pages to do.
    Is there any way to simple change color of everything at once, just from black to white ? Or do I have to go object by object manually ?
    Thank you very much, for all the help so far, and I'm sincerly sorry to waste your time if that has been covered previously.
    Good day
    ciao ciao
    Monika

    Thank you both for such prompt follow up. I know it's just typing and it's easy but I sincerly mean it. Thank you.
    The INVERT work on some images.
    The "SAME" seem to work funny way. When I select STROKE COLOR, it does nothing, but when I select WIGHT then it does and in fact I'm able to change lots of strokes at once with ease. Even tho I'm left with few small bits here and there which I need to change manually, it is certainly far better than doing one by one.
    Thanks a lot for the help, it's what I was looking for.
    By the way   I not once used the SAME menu. Feel so lame, given I use AI (not daily but often) for few years now... Shame.
    Thank you and you guys have a great day
    xoxo

  • Changing color of an object on stage during runtime? in Flash CS4 (AS3)

    Hi,
    I was wondering if there is a way to change the color of an object during runtime. any ideas?
    Thank you for helping.

    you can use the colortransform property of your objects transform property.  so, if you have a displayobject mc, you can use:
    var t:Transform = mc.transform
    var ct:ColorTransform = t.colorTransform;
    ct.color = 0xff0000;
    mc.transform.colorTransform = ct;

  • Applet to draw rectanlge changing color randomly

    hello ,
    i am new to java and learning applets . i want to draw a rectangle which changes its color randomly .
    my issue is i dont know how to set variable in
    function setColor()
    please help me to implement this applet .
    thanks in advance !
    gagan

    I've done something like so:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class AppletPanel extends JPanel
      private static final int DELAY = 160;
      private static final int RANDOM_COLOR_COUNT = 100;
      // use some of the standard colors in an array
      private Color[] colors =
        Color.white, Color.black, Color.red, Color.orange,
        Color.green, Color.blue, Color.cyan, Color.magenta, Color.YELLOW 
      private Color myColor = Color.white;
      List<Color> colorList = new ArrayList<Color>();
      private Random random = new Random();
      private int delay = DELAY;
      Timer timer = new Timer(delay, new ActionListener()
        public void actionPerformed(ActionEvent e)
          myColor = colorList.get(random.nextInt(colorList.size()));
          setBackground(myColor);
      public AppletPanel()
        setPreferredSize(new Dimension(250, 250));
        for (int i = 0; i < colors.length; i++)
          // here we use a Color List to hold the standard colors
          colorList.add(colors);
    for (int i = 0; i < RANDOM_COLOR_COUNT; i++)
    Color c = new Color(
    random.nextInt(256),
    random.nextInt(256),
    random.nextInt(256));
    // and now stuff the list with random colors too!
    colorList.add(c);
    timer.start();
    and for the applet part:
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JApplet;
    public class AppletPanelTest extends JApplet
      public void init()
        try
          javax.swing.SwingUtilities.invokeAndWait(new Runnable()
            public void run()
              createGUI();
        catch (Exception e)
          System.err.println("createGUI didn't successfully complete");
      private void createGUI()
        setSize(new Dimension(400, 300));
        AppletPanel panel = new AppletPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(panel);

  • How Do I change color randomly of a MovieClip in a Timer event?

    I have created a MovieClip named "Target" and called it from actionscript. Inside this movie clip I have created an 'action' layer and written the code in it:
    import fl.motion.Animator;
    import fl.motion.MotionEvent;
    var this_xml:XML = <Motion duration="30" xmlns="fl.motion.*" xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
        <source>
            <Source frameRate="12" x="202" y="169.15" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="Target">
                <dimensions>
                    <geom:Rectangle left="-32.05" top="-30.85" width="64.05" height="61.7"/>
                </dimensions>
                <transformationPoint>
                    <geom:Point x="0.5003903200624512" y="0.5"/>
                </transformationPoint>
            </Source>
        </source>
        <Keyframe index="0" tweenSnap="true" tweenSync="true">
            <tweens>
                <SimpleEase ease="0"/>
            </tweens>
        </Keyframe>
        <Keyframe index="29" scaleX="2.096" scaleY="2.096"/>
    </Motion>;
    var this_animator:Animator = new Animator(this_xml, this);
    this_animator.play();
    this_animator.addEventListener(MotionEvent.MOTION_END, removeTarget);
    function removeTarget(event:MotionEvent):void
        this.parent.removeChild(this);
    In the main timeline I also have created another 'action' layer and written the code like this:
    var timer:Timer;
    var targetCount:uint;
    var container:MovieClip;
    function initGame():void
        container = new MovieClip();
        addChild(container);
        targetCount = 10;
        timer = new Timer(1000, targetCount);
        timer.addEventListener(TimerEvent.TIMER, generateTarget);
        timer.start();
    function generateTarget(event:TimerEvent):void
        var target:MovieClip = new Target();
         target.x = Math.random() * stage.stageWidth;
        target.y = Math.random() * stage.stageHeight;
        container.addChild(target);
    initGame();
    Now I can get 10 animating circles in different places of the stage after every second. And every circles will leave the stage after completing the animation. Though I have given 'pink' color in that circle, that's why its generating with 'pink' color always. How do I change the color of each circle while it will generate?
    Regards
    Dipesh Pal.

    I have tried in this way......
    function generateTarget(event:TimerEvent):void
        var target:MovieClip = new Target();
        var colorT:ColorTransform = new ColorTransform();
        colorT.redOffset = Math.round(Math.random() * 510) - 255;
        colorT.greenOffset = Math.round(Math.random() * 510) - 255;
        target.transform.colorTransform = colorT;
        target.x = Math.random() * stage.stageWidth;
        target.y = Math.random() * stage.stageHeight;
        container.addChild(target);
    but its not working......
    infact i have used function 'circleColor' which holds this random color transform.... and call that function from 'generateTarget' function also....but it doesnt work too...
    then how do I change the color of every circle which is randomly generating in the stage....?

  • I cannot change color of vector object

    I bought an image from shutterstocks... But when I change a colour, it all turns in monochrome colour. My Ai (CS6) knowledge is very limited, so I do not know what to Google "How to..."
    I would say that in a moment I change colour Ai understands that I colour in borders and all lines overlaps each other... However, I do not colour borders...
    Image is very complex pattern and I believe it is somehow related with image production... The image does not appear as it looks like - everything is over layered with cut-outs of object above... But it is beyond my knowledge...
    I have tried to ungroup but with same results...
    Could you please explain how to manipulate this image? Thank you!

    If this helps, here is a print screan as I cannot uploud real image... This image consists of 1 layer that is divided in thons of paths and some Compound Paths...
    Thanks a lot!

  • Change Color of Line Object

    aLine.border.edge.color.value
    ="207,29,3";
    This doesnt work.. any suggestions?

    One last thing.
    On Initialize of the Parent Subform a Table belongs in I change the Header Fill color based on a variable.  Other instances of this Table gets added with a button click.. everything works find interms of the add.
    When I change the color though the new tables added do not take the new color of the initialize event.
    Is there a way I can do it on the add event?
    this.parent.instanceManager.addInstance(1);
    this.parent.instanceIndex< ??? >.execInitialize();

  • Changing color in JTable objects

    Hi all,
    I'm writing an application which shows tabular view of events of some outcome. Now I want to give color to each row depending on the severity of particular parameters in the table. I've written application using swings and using components JTable. Is there any way to give color to each depending on value so that I can give colors to each row Red, Blue and Green like that and all
    Waiting for your precious replies,
    With best regards,
    harry_sai

    Yes, you use a TableCellRenderer. Rather than explain further I'll just refer you to the tutorial about JTable.

  • How would I change JLabel and place object randomly

    hello, I am trying to make sort of a one-sided Battleship game and I have an 8X8 Grid-Layout and do have the MouseListener set up to when one is clicked the color changes. How can I make it so when one is clicked, the word "MISSED" or a graphic of a big X is layed across the appropriate square? Also, is it possible to lay an object down randomly over 3 or so different squares? Here's my code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    public class CreateBoard extends JFrame
    public static void main(String[] args)
    {   JFrame board = new CreateBoard();
    public CreateBoard()
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setPreferredSize(new Dimension(600,600));
    setTitle("BattleShip");
    getContentPane().setLayout(new GridLayout(8,8));
    for (int i = 0; i < 8; i++)
    {   for (int j = 0; j < 8; j++)
    getContentPane().add(new GameSpace());
    pack();
    setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class GameSpace extends JPanel
    {   GameSpace()
    setBackground(Color.WHITE);
    Border borderColor = BorderFactory.createLineBorder(Color.BLACK);
    setBorder(borderColor);
    addMouseListener(new MouseClickListener());
    class MouseClickListener extends MouseAdapter
    {   public void mouseClicked(MouseEvent evt)
    setBackground(Color.LIGHT_GRAY);
    repaint();
    Thanks

    You could perhaps make use of some JButtons.
    * Tweak the border property so noone can tell it's buttons (that is of course if you don't want anyone to see they are buttons...)
    * start with no text on the buttons
    * when a button is clicked -> change colors, put some text or icon on the button or something
    What I'm suggesting is basically that your GameSpace class extends JButton (or perhaps JToggleButton if you want to make use of two "states") instead of JPanel...

  • How can I change the color of a object inside a symbol?

    Hello!
    I'm working on this study and I need to change the color of an object inside a symbol when I click another object.
    The object is called "bola", wich is inside the symbol "ponto" and the clicking object are the colored pencils (each pencil should change the color of the symbol's object, giving the impression you'd selecting a different pencil to draw).
    I think it's simple to understand what I mean when you see the files.
    I already tried this line on click event of the pencils, but it didn't work:
    sym.getSymbol("ponto").$("bola").css("color","#123456");
    Anyone knows how to make that work?
    I would like to improve the experience of drawing as well. I made it with the "mousedown" event. Is that a better way to get a similar effect?
    My files
    Thanks a lot,
    Clayton F.

    Ok here is another sample:
    http://www.meschrene.puremadnessproductions.net/Samples/HELP/LapisB/Lapis.html
    http://www.meschrene.puremadnessproductions.net/Samples/HELP/LapisB/Lapis.zip
    You need to create a var that changes the css background color..
    Hopefully you can understand what I did...
    The text I left showing so that you could see it change...
    I updated the files and all colors should work now.
    Message was edited by: ♥Schrene

  • Changing the Color of an Object in Elements 4.0

    Neither of the two methods documented in Elements 4.0 to change the color of an object seem to work on my object. It is a fleur-de-lis that I extracted from a PDF an artist made for me some time ago. It's now black and I want to make it gold. What am I doing wrong?

    Harold McDougal wrote:
    The first is to select Enhance, Adjust Color, Change Color, select the color to be changed with the eye dropper and the color to change to in the bottom window. Then select okay. Okay. In my case, nothing happens.
    The color replacement command doesn't work on pure black or white. 
    If the design is black over white, try using a solid color fill and one of the lighten blend modes.
    How?
    Sample the gold color you want and have it as the foreground color chip.   Add a solid color adjustment layer over your  black and white design. The color should automatically be the foreground color in your tool box. Since should have changed this swatch to the desired shade of gold, it should be gold. Now, for the magic. If you change the blend mode of the solid color fill layer to "lighten", "screen", "linear dodge", or "lighter color", the black will be replaced by your gold.
    Note: I'm not sure which if any of the Elements versions includes the "lighter color" blend mode so if you can't find that one...don't panic.

  • Change color of object

    I have a image I am editing in photoshop CS, I want to replace the black color of an object with blue, I've done this in the past but for some reason the Contrast/brightness tool is not working, I can change the brightness but the object is just staying black. I tried using the magic wand and selecting the object and then fillinf it but that leaves uneven edges.

    Have you tried enabling the tint checkbox? That can be used to add color. (if necessary you can use a selection to create the mask for the hue/saturation/luminance adjustment layer).
    Another solution is to create a selection for the black area, then with a new layer add a mask to it and fill that layer with a color (not necessarily in that order) then you can use a blend mode or opacity to allow any texture to show through if there is any.

  • Why can't I change the color of an object?

    I am having trouble with the color brick. I can't change the color of an object, at least not like described here: http://http://thedigitalstory.com/2012/12/easily-color-changin.html.
    Some background:
    1. I am working with RAW files.
    2. I have RTFM.
    3. I have consulted three books I own on Aperture.
    4. I have searched the web for help, which is how I came across the link above.
    5. I am using the color block correctly, but I can only achieve a subtle shift in the change of very pale colors. This is despite adding up to three additional color blocks to try to increase the degree of change, but there is no way I am coming close to being able to change a blue car to purple, let alone to red (this references the link above.)
    Others must have experienced this, I would think. Any thoughts on what I might do differently to achieve more dramatic results from the color block? I don't even have a specific change in a specific image that I'm asking about—I just want to master the software so that I can do so when I need to. Come to think of it, there is a specific change I want to make in a image. Now it's really an important question!
    Thanks,
    Ben

    Thanks, Léonie.  A quick way to move any slider to its extreme is to click on the value in the Value Slider and drag all the way left or right.  This is much faster than side-stepping all the way to the far limits.
    I think the example the OP (Ben) is trying to emulate is misleading (given the sophistication of the Digital Story poster, deliberately, and wrongly, so).  The car in the original photo is just about the only blue object (and thus pixels) in the image used to demonstrate that one can change the hue of objects using Aperture.  Aperture excels at global adjustments and adjustments made to _imprecisely_ bounded areas.  (This is, contrary to one's expectation, one of Aperture's great strengths: imprecisely-bounded tone and hue shifts are perceived as "natural"; precisely bounded ones look "artificial".  Most photographers (as opposed to graphic artists) wish to retain the illusion of a natural world inside their pictures.)  The only reason the hue-changing trick works with the car in the photo is that the Color adjustment effects only the car because it is the only blue object in the photo (there is a bluish TV in the background, and a bluish logo on one of the displays in the background).
    The point is that while object-specific hue-shifts can be made with Aperture, it is not the program of choice for this kind of editing.  A graphics package, which allows for much more control over selecting pixels, is recommended.

  • Why can't I change colors of objects?

    why can't I change colors of objects?

    Thanks KT.  I did mean the Fill color, but my real issue is that changing the fill color in the inspector doesn't change the color of the selected object.  In tis case, I was trying to chnage the fill color from pale blue to the more ingense blue:

Maybe you are looking for