Setter Race Animation : Animation « Swing Components « Java






Setter Race Animation

Setter Race Animation


import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.interpolation.PropertySetter;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.UIManager;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.Point;
import javax.swing.JComponent;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

/*
 * SetterRace.java
 *
 * Created on May 3, 2007, 2:37 PM
 *
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Like BasicRace, only this version uses the property setter capabilities
 * of the framework.  Instead of manually calculating the position of the
 * car, we have the framework do it for us, based on how we set up the
 * PropertySetter object.  All of this is done at
 * construction time and we merely start or stop the animation based on
 * the Go/Stop buttons at runtime.
 *
 * @author Chet
 */
public class SetterRace implements ActionListener {
    
    protected Animator timer;
    public static final int RACE_TIME = 2000;
    
    
    /** Creates a new instance of BasicRace */
    public SetterRace(String appName) {
        RaceGUI basicGUI = new RaceGUI(appName);
        
        // Now set up an animation that will automatically
        // run itself with PropertySetter
        timer = PropertySetter.createAnimator(RACE_TIME, basicGUI.getTrack(), 
                "carPosition", TrackView.START_POS, TrackView.FIRST_TURN_START);
        basicGUI.getControlPanel().addListener(this);
    }
    
    public static void main(String args[]) {
        Runnable doCreateAndShowGUI = new Runnable() {
            public void run() {
                SetterRace race = new SetterRace("Property Setter Race");
            }
        };
        SwingUtilities.invokeLater(doCreateAndShowGUI);
    }
    
    /**
     * Handles clicks on Go/Stop buttons to start/stop the animation
     */
    public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("Go")) {
            if (timer != null) {
                timer.stop();
                timer.start();
            } else {
                timer.start();
            }
        } else if (ae.getActionCommand().equals("Stop")) {
            if (timer != null) {
                timer.stop();
            }
        }
    }
}
/**
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



/**
 * The GUI used by all of the different race demos.
 * It contains a control panel (for the Go/Stop buttons) and a
 * TrackView (where the race is rendered)
 *
 * @author Chet
 */
class RaceGUI {

    private TrackView track;
    private RaceControlPanel controlPanel;

    /**
     * Creates a new instance of RaceGUI
     */
    public RaceGUI(String appName) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        JFrame f = new JFrame(appName);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new BorderLayout());
        
        // Add Track view
        track = new TrackView();
        f.add(track, BorderLayout.CENTER);
        
        // Add control panel
        controlPanel = new RaceControlPanel();
        f.add(controlPanel, BorderLayout.SOUTH);
        
        f.pack();
        f.setVisible(true);
    }
    
    public TrackView getTrack() {
        return track;
    }
    
    public RaceControlPanel getControlPanel() {
        return controlPanel;
    }
}
/**
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



/**
 * This class does the work of rendering the current view of the
 * racetrack.  It holds the car position and rotation and displays
 * the car accordingly.  The track itself is merely a background image
 * that is copied the same on every repaint.
 * Note that carPosition and carRotation are both JavaBean properties, which
 * is exploited in the SetterRace and MultiStepRace variations.
 *
 * @author Chet
 */
class TrackView extends JComponent {
    
    BufferedImage car;
    BufferedImage track;
    Point carPosition;
    double carRotation = 0;
    int trackW, trackH;
    int carW, carH, carWHalf, carHHalf;

    /** Hard-coded positions of interest on the track */
    static final Point START_POS = new Point(450, 70);
    static final Point FIRST_TURN_START = new Point(130, 70);
    static final Point FIRST_TURN_END = new Point(76, 127);
    static final Point SECOND_TURN_START = new Point(76, 404);
    static final Point SECOND_TURN_END = new Point(130, 461);
    static final Point THIRD_TURN_START = new Point(450, 461);
    static final Point THIRD_TURN_END = new Point(504, 404);
    static final Point FOURTH_TURN_START = new Point(504, 127);
    
    /** Creates a new instance of TrackView */
    public TrackView() {
        try {
            car = ImageIO.read(TrackView.class.getResource("beetle_red.gif"));
            track = ImageIO.read(TrackView.class.getResource("track.jpg"));
        } catch (Exception e) {
            System.out.println("Problem loading track/car images: " + e);
        }
        carPosition = new Point(START_POS.x, START_POS.y);
        carW = car.getWidth();
        carH = car.getHeight();
        carWHalf = carW / 2;
        carHHalf = carH / 2;
        trackW = track.getWidth();
        trackH = track.getHeight();
    }
    
    public Dimension getPreferredSize() {
        return new Dimension(trackW, trackH);
    }
    
    /**
     * Render the track and car
     */
    public void paintComponent(Graphics g) {
        // First draw the race track
        g.drawImage(track, 0, 0, null);
        
        // Now draw the car.  The translate/rotate/translate settings account
        // for any nonzero carRotation values
        Graphics2D g2d = (Graphics2D)g.create();
        g2d.translate(carPosition.x, carPosition.y);
        g2d.rotate(Math.toRadians(carRotation));
        g2d.translate(-(carPosition.x), -(carPosition.y));
        
        // Now the graphics has been set up appropriately; draw the
        // car in position
        g2d.drawImage(car, carPosition.x - carWHalf, carPosition.y - carHHalf, null);
    }
    
    /**
     * Set the new position and schedule a repaint
     */
    public void setCarPosition(Point newPosition) {
        repaint(0, carPosition.x - carWHalf, carPosition.y - carHHalf,
                carW, carH);
        carPosition.x = newPosition.x;
        carPosition.y = newPosition.y;
        repaint(0, carPosition.x - carWHalf, carPosition.y - carHHalf,
                carW, carH);
    }
    
    /**
     * Set the new rotation and schedule a repaint
     */
    public void setCarRotation(double newDegrees) {
        carRotation = newDegrees;
        // repaint area accounts for larger rectangular are because rotate
        // car will exceed normal rectangular bounds
        repaint(0, carPosition.x - carW, carPosition.y - carH,
                2 * carW, 2 * carH);
    }
        
}
/**
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



/**
 * Go/Stop buttons to control the animation
 *
 * @author Chet
 */
class RaceControlPanel extends JPanel {
    
    /** Make these static so that outside classes can easily
     *  add themselves as listeners */
    JButton goButton = new JButton("Go");
    JButton stopButton = new JButton("Stop");

    /**
     * Creates a new instance of RaceControlPanel
     */
    public RaceControlPanel() {
        add(goButton);
        add(stopButton);
    }
    
    public JButton getGoButton() {
        return goButton;
    }
    
    public JButton getStopButton() {
        return stopButton;
    }
    
    public void addListener(ActionListener listener) {
        goButton.addActionListener(listener);
        stopButton.addActionListener(listener);
    }
    
}


           
       








Filthy-Rich-Clients-SetterRace.zip( 480 k)

Related examples in the same category

1.Pulse AnimationPulse Animation
2.Pulse Animation FieldPulse Animation Field
3.Fade In ButtonFade In Button
4.Fade In DemoFade In Demo
5.Morphing DemoMorphing Demo
6.Component Transition AnimationComponent Transition Animation
7.Animation By jdesktop animation
8.Animator Setup
9.Basic Race with AnimationBasic Race with Animation
10.Discrete Interpolation
11.Multi Step RaceMulti Step Race
12.NonLinear Race DemoNonLinear Race Demo
13.Spline Interpolator TestSpline Interpolator Test
14.Animation TriggerAnimation Trigger
15.Trigger Race AnimationTrigger Race Animation
16.Tumble Item Project