hi guys,
im trying to implement the following into my java app code:
Here's my code: first ill post the main class, then the animation panel class, then moving shape and moving rectangle class...the additional files like the shape gif and path gifs are here, youll also find all the info need in here and the code files:
here's the main
/* * ============================================================= * A1.java : Extends JApplet and contains a panel where * shapes move around on the screen. Also contains start and stop * buttons that starts animation and stops animation respectively. * ============================================================== */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; import javax.swing.event.*; import java.util.Vector; public class A1 extends JApplet { AnimationPanel panel; // panel for bouncing area JButton startButton, stopButton; //buttons to start and stop the animation /** main method for A1 */ public static void main(String[] args) { A1 applet = new A1(); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(applet, BorderLayout.CENTER); frame.setTitle("Bouncing Application"); applet.init(); applet.start(); frame.setSize(500, 500); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); frame.setLocation((d.width - frameSize.width) / 2, (d.height - frameSize.height) / 2); frame.setVisible(true); } /** init method to initialise components */ public void init() { panel = new AnimationPanel(); add(panel, BorderLayout.CENTER); add(setUpToolsPanel(), BorderLayout.NORTH); add(setUpButtons(), BorderLayout.SOUTH); addComponentListener( new ComponentAdapter() { // resize the frame and reset all margins for all shapes public void componentResized(ComponentEvent componentEvent) { panel.resetMarginSize(); } }); } /** Set up the tools panel * @return toolsPanel the Panel */ public JPanel setUpToolsPanel() { //Set up the shape combo box ImageIcon rectangleButtonIcon = createImageIcon("rectangle.gif"); JComboBox<ImageIcon> shapesComboBox = new JComboBox<ImageIcon>(new ImageIcon[] {rectangleButtonIcon} ); shapesComboBox.setToolTipText("Set shape"); shapesComboBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); //set the default shape type based on the selection: 0 for Circle, 1 for Rectangle panel.setCurrentShapeType(cb.getSelectedIndex()); } }); //Set up the path combo box ImageIcon fallingButtonIcon = createImageIcon("falling.gif"); ImageIcon boundaryButtonIcon = createImageIcon("boundary.gif"); JComboBox<ImageIcon> pathComboBox = new JComboBox<ImageIcon>(new ImageIcon[] {boundaryButtonIcon, fallingButtonIcon}); pathComboBox.setToolTipText("Set Path"); pathComboBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); //set the default path type based on the selection from combo box: 0 for Boundary Path, 1 for Falling Path panel.setCurrentPathType(cb.getSelectedIndex()); } }); //Set up the height TextField JTextField heightTxt = new JTextField("20"); heightTxt.setToolTipText("Set Height"); heightTxt.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField tf = (JTextField)e.getSource(); try { int newValue = Integer.parseInt(tf.getText()); if (newValue > 0) panel.setCurrentHeight(newValue); } catch (Exception ex) { tf.setText("20"); } } }); //Set up the width TextField JTextField widthTxt = new JTextField("20"); widthTxt.setToolTipText("Set Width"); widthTxt.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField tf = (JTextField)e.getSource(); try { int newValue = Integer.parseInt(tf.getText()); if (newValue > 0) panel.setCurrentWidth(newValue); } catch (Exception ex) { tf.setText("20"); } } }); JPanel toolsPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx=1; add(toolsPanel, new JLabel(" Shape: ", JLabel.RIGHT), gbc, 0, 0, 1, 1); add(toolsPanel, shapesComboBox, gbc, 1, 0, 1, 1); add(toolsPanel, new JLabel(" Path: ", JLabel.RIGHT), gbc, 2, 0, 1, 1); add(toolsPanel, pathComboBox, gbc, 3, 0, 1, 1); add(toolsPanel, new JLabel(" Height: ", JLabel.RIGHT), gbc, 4, 0, 1, 1); add(toolsPanel, heightTxt, gbc, 5, 0, 1, 1); add(toolsPanel, new JLabel(" Width: ", JLabel.RIGHT), gbc, 6, 0, 1, 1); add(toolsPanel, widthTxt, gbc, 7, 0, 1, 1); return toolsPanel; } /** Set up the buttons panel * @return buttonPanel the Panel */ public JPanel setUpButtons() { JPanel buttonPanel= new JPanel(new FlowLayout()); //Set up the start button startButton = new JButton("Start"); startButton.setToolTipText("Start Animation"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { startButton.setEnabled(false); stopButton.setEnabled(true); panel.start(); //start the animation } }); //Set up the stop button stopButton = new JButton("Stop"); stopButton.setToolTipText("Stop Animation"); stopButton.setEnabled(false); stopButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { stopButton.setEnabled(false); startButton.setEnabled(true); //stop the animation panel.stop(); } }); // Slider to adjust the speed of the animation JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 200, 30); slider.setToolTipText("Adjust Speed"); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int value = (int) (source.getValue()); // get the value from slider TitledBorder tb = (TitledBorder) source.getBorder(); tb.setTitle("Anim delay = " + String.valueOf(value) + " ms"); //adjust the tilted border to indicate the speed of the animation panel.adjustSpeed(value); //set the speed source.repaint(); } } }); TitledBorder title = BorderFactory.createTitledBorder("Anim delay = 30 ms"); slider.setBorder(title); // Add buttons and slider control buttonPanel.add(startButton); buttonPanel.add(stopButton); buttonPanel.add(slider); return buttonPanel; } /** create the imageIcon * @param filename the filename of the image * @return ImageIcon the imageIcon */ protected static ImageIcon createImageIcon(String filename) { java.net.URL imgURL = A1.class.getResource(filename); return new ImageIcon(imgURL); } /** Adds a component to a Panel. @param p is the panel @param c is the component to add @param gbc the grid bag constraints @param x the grid bag column @param y the grid bag row @param w the number of grid bag columns spanned @param h the number of grid bag rows spanned */ private void add(JPanel p, Component c, GridBagConstraints gbc, int x, int y, int w, int h) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; p.add(c, gbc); } }
Here's the Animation panel class:
/* * ====================================================================== * AnimationPanel.java : Moves shapes around on the screen according to different paths. * It is the main drawing area where shapes are added and manipulated. * It also contains a popup menu to clear all shapes. * ====================================================================== */ import javax.swing.*; import java.awt.*; import java.util.*; import java.awt.event.*; public class AnimationPanel extends JComponent implements Runnable { private Thread animationThread = null; // the thread for animation private ArrayList<MovingShape> shapes; // the arraylist to store all shapes private int currentShapeType, // the current shape type currentPath, // the current path type currentWidth = 20, // the current width of a shape currentHeight = 20; // the current height of a shape private int delay = 30; // the current animation speed JPopupMenu popup; // popup menu /** Constructor of the AnimationPanel */ public AnimationPanel() { shapes = new ArrayList<MovingShape>(); //create the vector to store shapes popup = new JPopupMenu(); //create the popup menu makePopupMenu(); // add the mouse event to handle popup menu and create new shape addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseClicked( MouseEvent e ) { if (animationThread != null) { // if the animation has started, then boolean found = false; MovingShape currentShape = null; for (int i = 0; i < shapes.size(); i++) { currentShape = shapes.get(i); if ( currentShape.contains( e.getPoint()) ) { // if the mousepoint is within a shape, then set the shape to be selected/deselected found = true; currentShape.setSelected( ! currentShape.isSelected() ); System.out.println(currentShape); } } if (! found) createNewShape(e.getX(), e.getY()); // if the mousepoint is not within a shape, then create a new one according to the mouse position } } }); } /** create a new shape * @param x the x-coordinate of the mouse position * @param y the y-coordinate of the mouse position */ protected void createNewShape(int x, int y) { // get the margin of the frame Insets insets = getInsets(); int marginWidth = getWidth() - insets.left - insets.right; int marginHeight = getHeight() - insets.top - insets.bottom; // create a new shape dependent on all current properties and the mouse position switch (currentShapeType) { case 0: { //rectnage shapes.add( new MovingRectangle(x, y, currentWidth, currentHeight, marginWidth, marginHeight, currentPath)); break; } } } /** set the current shape type * @param s the new shape type */ public void setCurrentShapeType(int s) { currentShapeType = s; } /** set the current path type and the path type for all currently selected shapes * @param t the new path type */ public void setCurrentPathType(int t) { currentPath = t; MovingShape currentShape = null; for (int i = 0; i < shapes.size(); i++) { currentShape = shapes.get(i); if ( currentShape.isSelected()) { currentShape.setPath(currentPath); } } } /** set the current width and the width for all currently selected shapes * @param w the new width value */ public void setCurrentWidth(int w) { MovingShape currentShape = null; currentWidth = w; for (int i = 0; i < shapes.size(); i++) { currentShape = shapes.get(i); if ( currentShape.isSelected()) { currentShape.setWidth(currentWidth); } } } /** set the current height and the height for all currently selected shapes * @param h the new height value */ public void setCurrentHeight(int h) { MovingShape currentShape = null; currentHeight = h; for (int i = 0; i < shapes.size(); i++) { currentShape = shapes.get(i); if ( currentShape.isSelected()) { currentShape.setHeight(currentHeight); } } } /** remove all shapes from our vector */ public void clearAllShapes() { shapes.clear(); } // you don't need to make any changes after this line ______________ /** create the popup menu for our animation program */ protected void makePopupMenu() { JMenuItem menuItem; // clear all menuItem = new JMenuItem("Clear All"); menuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { clearAllShapes(); } }); popup.add(menuItem); } /** reset the margin size of all shapes from our vector */ public void resetMarginSize() { Insets insets = getInsets(); int marginWidth = getWidth() - insets.left - insets.right; int marginHeight = getHeight() - insets.top - insets.bottom ; for (int i = 0; i < shapes.size(); i++) ( shapes.get(i)).setMarginSize(marginWidth, marginHeight); } /** update the painting area * @param g the graphics control */ public void update(Graphics g){ paint(g); } /** move and paint all shapes within the animation area * @param g the Graphics control */ public void paintComponent(Graphics g) { MovingShape currentShape; for (int i = 0; i < shapes.size(); i++) { currentShape = shapes.get(i); currentShape.move(); currentShape.draw(g); } } /** change the speed of the animation * @param newValue the speed of the animation in ms */ public void adjustSpeed(int newValue) { if (animationThread != null) { stop(); delay = newValue; start(); } } /** When the "start" button is pressed, start the thread */ public void start() { animationThread = new Thread(this); animationThread.start(); } /** When the "stop" button is pressed, stop the thread */ public void stop() { if (animationThread != null) { animationThread = null; } } /** run the animation */ public void run() { Thread myThread = Thread.currentThread(); while(animationThread==myThread) { repaint(); pause(delay); } } /** Sleep for the specified amount of time */ private void pause(int milliseconds) { try { Thread.sleep((long)milliseconds); } catch(InterruptedException ie) {} } }
Here's the MovingShape Class:
/* * =============================================================================== * MovingShape.java : The superclass of all shapes. * A shape has a point (top-left corner). * A shape defines various properties, including selected, colour, width and height. * =============================================================================== */ import java.awt.*; public abstract class MovingShape { public int marginWidth, marginHeight; // the margin of the animation panel area protected Point p; // the top left coner of shapes protected int width; // the width of shapes protected int height; // the height of shapes protected MovingPath path; // the moving path of shapes protected boolean selected = false; // draw handles if selected /** constuctor to create a shape with default values */ public MovingShape() { this(0, 0, 20, 20, 500, 500, 0); // the default properties } /** constuctor to create a shape * @param x the x-coordinate of the new shape * @param y the y-coordinate of the new shape * @param w the width of the new shape * @param h the height of the new shape * @param mw the margin width of the animation panel * @param mh the margin height of the animation panel * @param typeOfPath the path of the new shape */ public MovingShape(int x, int y, int w, int h, int mw, int mh, int pathType) { p = new Point(x,y); marginWidth = mw; marginHeight = mh; width = w; height = h; setPath (pathType); } /** Return the x-coordinate of the shape. * @return the x coordinate */ public int getX() { return p.x; } /** Return the y-coordinate of the shape. * @return the y coordinate */ public int getY() { return p.y;} /** Return the selected property of the shape. * @return the selected property */ public boolean isSelected() { return selected; } /** Set the selected property of the shape. * When the shape is selected, its handles are shown. * @param s the selected value */ public void setSelected(boolean s) { selected = s; } /** Set the width of the shape. * @param w the width value */ public void setWidth(int w) { width = w; } /** Set the height of the shape. * @param h the height value */ public void setHeight(int h) { height = h; } /** * Return a string representation of the shape, containing * the String representation of each element. */ public String toString() { return "[" + this.getClass().getName() + "," + p.x + "," + p.y + "]"; } /** Draw the handles of the shape * @param g the Graphics control */ public void drawHandles(Graphics g) { // if the shape is selected, then draw the handles if (isSelected()) { g.setColor(Color.black); g.fillRect(p.x -2, p.y-2, 4, 4); g.fillRect(p.x + width -2, p.y + height -2, 4, 4); g.fillRect(p.x -2, p.y + height -2, 4, 4); g.fillRect(p.x + width -2, p.y-2, 4, 4); } } /** Reset the margin for the shape * @param w the margin width * @param h the margin height */ public void setMarginSize(int w, int h) { marginWidth = w; marginHeight = h; } /** abstract contains method * Returns whether the point p is inside the shape or not. * @param p the mouse point */ public abstract boolean contains(Point p); /** abstract draw method * draw the shape * @param g the Graphics control */ public abstract void draw(Graphics g); /** Set the path of the shape. * @param pathID the integer value of the path * MovingPath.BOUNDARY is the boundary path * MovingPath.FALLING is the falling path */ public void setPath(int pathID) { switch (pathID) { case MovingPath.BOUNDARY : { path = new BoundaryPath(10, 10); break; } case MovingPath.FALLING : { path = new FallingPath(); break; } } } /** move the shape by the path */ public void move() { path.move(); } // Inner class ===================================================================== Inner class /* * =============================================================================== * MovingPath : The superclass of all paths. It is an inner class. * A path can change the current position of the shape. * =============================================================================== */ public abstract class MovingPath { public static final int BOUNDARY = 0; // The Id of the moving path public static final int FALLING = 1; // The Id of the moving path protected int deltaX, deltaY; // moving distance /** constructor */ public MovingPath() { } /** abstract move method * move the shape according to the path */ public abstract void move(); } /* * =============================================================================== * FallingPath : A falling path. * =============================================================================== */ public class FallingPath extends MovingPath { private double am = 0, stx =0, sinDeltax = 0; /** constructor to initialise values for a falling path */ public FallingPath() { am = Math.random() * 20; //set amplitude variables stx = 0.5; //set step variables deltaY = 5; sinDeltax = 0; } /** move the shape */ public void move() { sinDeltax = sinDeltax + stx; p.x = (int) Math.round(p.x + am * Math.sin(sinDeltax)); p.y = p.y + deltaY; if (p.y > marginHeight) // if it reaches the bottom of the frame, start again from the top p.y = 0; } } /* * =============================================================================== * BoundaryPath : A boundary path which moves the shape around the boundary of the frame * =============================================================================== */ public class BoundaryPath extends MovingPath { private int direction; /** constructor to initialise values for a boundary path */ public BoundaryPath(int speedx, int speedy) { deltaX = (int) (Math.random() * speedx) + 1; deltaY = (int) (Math.random() * speedy) + 1; direction = 0; } /** move the shape */ public void move() { int h = marginHeight - height; int w = marginWidth - width; switch (direction) { case 0 : { // move downwards p.y += deltaY; if (p.y > h) { p.y = h - 1; direction = 90; } break; } case 90 : { // move to the right p.x += deltaX; if (p.x > w) { p.x = w - 1; direction = 180; } break; } case 180 : { p.y -= deltaY; // move upwards if (p.y < 0) { direction = 270; p.y = 0; } break; } case 270 : { // move to the left p.x -= deltaX; if (p.x < 0) { direction = 0; p.x = 0; } break; } } } } // ======================================================================================== }
and finally here's the moving rectangle class:
/* * =============================================================================== * MovingRectangle.java : A shape that is a rectangle. * A rectangle has 4 handles shown when it is selected (by clicking on it). * =============================================================================== */ import java.awt.*; public class MovingRectangle extends MovingShape { /** constuctor to create a rectangle with default values */ public MovingRectangle() { super(); } /** constuctor to create a rectangle shape */ public MovingRectangle(int x, int y, int w, int h, int mw, int mh, int pathType) { super(x ,y ,w, h ,mw ,mh ,pathType); } /** draw the rectangle with the fill colour * If it is selected, draw the handles * @param g the Graphics control */ public void draw(Graphics g) { g.setColor(Color.blue); g.fillRect(p.x, p.y, width, height); g.setColor(Color.black); g.drawRect(p.x, p.y, width, height); drawHandles(g); } /** Returns whether the point is in the rectangle or not * @return true if and only if the point is in the rectangle, false otherwise. */ public boolean contains(Point mousePt) { return (p.x <= mousePt.x && mousePt.x <= (p.x + width + 1) && p.y <= mousePt.y && mousePt.y <= (p.y + height + 1)); } }