Solved

problem with rotating..

Posted on 2000-04-26
10
953 Views
Last Modified: 2008-02-01
I want the working code for simulation of a running fan using awt graphics object

Tha fan looks like this. A circle is to be drawn in which 4 triangles are to be drawn with one up, one down, one to the left and one to right.
I should be able to rotate this fan using multithreading..
please help me asap. I want the working code for this as I am new to java

0
Comment
Question by:bhumi042500
  • 6
  • 4
10 Comments
 
LVL 7

Accepted Solution

by:
Sasha_Mapa earned 40 total points
Comment Utility

public class MyApplet extends Applet implements Runnable{

  private final static int DELAY = 300;
  private final static int SPIN_ANGLE = Math.PI/6;
  private double currentAngle = 0;
  private boolean stop;


  public void start(){
     stop = false;
     Thread myThread = new Thread(this);
     myThread.start();
  }

 
  public void paint(Graphics g){
     drawFan(g,currentAngle);
  }

 
  public static void drawFan(Graphics g, double angle){
     // Implement drawing a fan at the given angle using the
     // various methods in java.awt.Graphics
  }

  public void run(){
    while(!stop){
       try{
         Thread.sleep(DELAY);
       } catch (InterruptedException e){
             System.out.println("spinning fan was interrupted");
             return;
          }
        currentAngle+=SPIN_ANGLE;
        repaint();
     }
  }

  public void stop(){
    stop = true;
  }
}



This will make the fan spin, but might cause flickering. To avoid the flickering, put this method in the class too:

public void update(Graphics g){
  Image dbImage = createImage(bounds().width,bounds().height);
  Graphics dbGraphics = gbImage.getGraphics();
  dbGraphics.setColor(getBackground());
  dbGraphics.fillRect(0,0,bounds().width,bounds().height);
  dbGraphics.setColor(getForeground());
  paint(dbGraphics);
  g.drawImage(gbImage,0,0,this);
}


Here's the explanation on how all this works.
The MyApplet class implements the method run(), which is the only method in the Runnable interface. When you instantiate Thread with a Runnable object as argument, the thread will execute the run() method of the Runnable object you gave it. I gave it "this" meaning, this instance of MyApplet, so when I call myThread.start() I am calling the run() method of the applet, only in another thread. The run method sleeps for the DELAY number of milliseconds, changes the current angle of the fan, and asks the applet to repaint itself. The applet knows how to paint itself at the current angle. When the applet is stopped by the browser (or appletviewer), its stop() method is called. The stop() method sets the variable stop to true which causes the run() method to exit, thus stopping our fan.

The part with the update(Graphics) method is called double buffering. It is done to prevent flickering caused by the fact that when you draw directly to the screen, you must fill it with the background color first, and there is some period of time when the user sees a blank screen filled with the background. Double buffering uses an ofscreen image to paint on that image and only after it is completely drawn, it draws that image on the screen. That way the user never sees a clear screen, thus no flickering :-)
0
 

Author Comment

by:bhumi042500
Comment Utility
Thanks Sasha

but how do i do the graphical part. You did not implement the drawFan method. I am not able to do the rotation of the line. Would you please help me out and give me the implementation of drawLine.
I really appreciate it
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
Comment Utility
Sorry, I can't give you a complete implementation, as this is probably a homework assignment. Use the following methods of the java.awt.Graphics class:

public abstract void
drawLine(int x1, int y1, int x2, int y2)

     Draws a line from (x1,y1) to (x2,y2)  in this graphics context's coordinate system.

     The line is drawn below and to the right of the logical coordinates.

     Parameters:
          x1 - the first point's x coordinate
          y1 - the first point's y coordinate
          x2 - the second point's x coordinate
          y2 - the second point's y coordinate





public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)

     Draws a single circular or elliptical arc that is filled with this graphics context's current color. The result is a pie shape.

     The center of the arc is the center of the rectangle whose origin is  and whose size is specified by the width and height arguments.

     The two axes of the arc are given by the width and height arguments.

     The arc is drawn from startAngle to startAngle + arcAngle. The start angle and arc angle are in degrees, not radians.

     A start angle of 0 indicates the 3-o'clock position. A positive arc angle indicates a counter-clockwise rotation; a negative
     arc angle indicates a clockwise rotation.
0
 

Author Comment

by:bhumi042500
Comment Utility
Thanks again

Will I be able to do this using the drawPoligon also. because with drawLine  I am able to draw thet line and arc seperately but I am not not able to rotate it and and join the tips with the arc.

Also please tell how I can move my fan in counter clock wise and also how do I vary the speed of it

Thanks again
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
Comment Utility
You will not need the drawLine (sorry). You actually only need the fillArc method. It would fill a sector of a circle for you, and to do an image of a fan you don't need anything else.
To vary the speed, play with the DELAY and the SPIN_ANGLE constants I defined (make sure you understand what each of them does!!). To move it counter clockwise, change the SPIN_ANGLE constant to be negative.

Please read the code I suggested, I am sure that if you would have read it carefully, you would have understood that changing the constants above will change direction and speed.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:bhumi042500
Comment Utility
Hello Sasha

I have solved my problem. But i dont know why I got confused with the canvas thing. The final code is not working.  I have designed mu GUI and it's giving me some problems. My Applet has to be like this
Create a subclass of canvas to display the fan. This subclass also contains the methods to suspend and resume the fan and the method for setting the fan's speed and reversing the fan's direction

I desigened the buttons and the canvas also
My code is like this


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import java.applet.*;

public class RunningFanApplet extends MyFrameWithExitHandling
  implements ActionListener
{
  private FanCanvas fc;

  //declare group control buttons
  private Button btStart, btStop, btReverse;

  public void init()
  {
      Frame f = new RunningFanApplet();
    f.setSize(500,260);
    f.setVisible(true);
    f.setTitle("Fan Applet");
    f.setBackground(Color.white);


    //create a FanCanvas instance
      fc = new FanCanvas();
      fc.setBackground(Color.yellow);
      fc.setForeground(Color.black);
      fc.setSize(300,50);


    //create a Panel for buttons
    Panel p2 = new Panel();
    p2.setLayout(new FlowLayout());
    p2.add(btStart = new Button("Start"));
    p2.add(btStop = new Button("Stop"));
    p2.add(btReverse = new Button("Reverse"));


    //add panels in the frame
    setLayout(new BorderLayout());
    add("Center", fc);
    add("South",p2);

    //setForeground(Color.black);
    //setBackground(Color.white);
    //register this frame as a listener on the buttons
    btStart.addActionListener(this);
    btStop.addActionListener(this);
    btReverse.addActionListener(this);
  }

  //button handler
  public void actionPerformed(ActionEvent e)
  {
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof Button)
    {
      if ("Start".equals((String)actionCommand))
      {
        //start the fan
        fc.start();

      }
      else if ("Stop".equals((String)actionCommand))
      {
        //stop the fan
        fc.stop();
      }
      else if ("Reverse".equals((String)actionCommand))
      {
        //reverse the fan
        fc.reverse();

      }
    }
  }
}

class FanCanvas extends Canvas implements Runnable
 {
  private int xcenter, ycenter;
  private int fanRadius;
  private final static int DELAY = 300;
  private final static int SPIN_ANGLE = (int)(Math.PI/6);
  private double currentAngle = 0;
  private boolean stop;

  public FanCanvas()
      {
       stop = false;
       //create the thread
       Thread myThread = new Thread(this);

     //start the thread
       myThread.start();
      }

  public void run()
   {
    while(!stop)
     {
       try
            {
          Thread.sleep(DELAY);
         }
         catch (InterruptedException e)
         {
          System.out.println("spinning fan was interrupted");
          return;
         }
         currentAngle+=SPIN_ANGLE;
         repaint();
       }
    }


   public void start()
    {
      if (!stop)
       {
        stop = false;
        //notify();
       }
     }

   public void stop()
    {
      stop = true;
    }

   public void reverse()
     {

      }


   public void paint(Graphics g)
     {
         // Implement drawing a fan at the given angle using the
         // various methods in java.awt.Graphics
         //get fan radius and center
         fanRadius = (int)(Math.min(getSize().width, getSize().height)*0.7*0.5);
         xcenter = (getSize().width)/2;
         ycenter = (getSize().height)/2;

         //draw circle
         g.setColor(Color.red);
         g.drawOval(xcenter - fanRadius,ycenter - fanRadius,
                  2*fanRadius, 2*fanRadius);

         int sLength = (int)(fanRadius*1.1);
         int x = sLength;
         int y = sLength;

         g.fillArc(xcenter - fanRadius, ycenter - fanRadius, 2*fanRadius-20, 2*fanRadius-20, 0, 25);
         g.fillArc(xcenter - fanRadius, ycenter - fanRadius, 2*fanRadius-20, 2*fanRadius-20, 90, 25);
         g.fillArc(xcenter - fanRadius, ycenter - fanRadius, 2*fanRadius-20, 2*fanRadius-20, 180, 25);
         g.fillArc(xcenter - fanRadius, ycenter - fanRadius, 2*fanRadius-20, 2*fanRadius-20, 270, 25);


    }

}


Please tell me whats wrong with this. I am running out of time

Thanks a lot
 
0
 

Author Comment

by:bhumi042500
Comment Utility
Sasha

I forgot to mention about MyFrameWithHandling..
It's just a class to class whisc impements WindowListener and is used to close the window

code for MyFrameWithExitHandling is

import java.awt.*;
import java.awt.event.*;

public class MyFrameWithExitHandling extends Frame
  implements WindowListener
{
  public static void main(String[] args)
  {
    Frame f = new MyFrameWithExitHandling("Test Frame");
    f.setSize(200,150);
    f.setVisible(true);
  }

  public MyFrameWithExitHandling(String str)
  {
    super(str);
    addWindowListener(this);
  }

  public MyFrameWithExitHandling()
  {
    super();
    addWindowListener(this);
  }

  public void windowClosed(WindowEvent event)
  {
  }

  public void windowDeiconified(WindowEvent event)
  {
  }

  public void windowIconified(WindowEvent event)
  {
  }

  public void windowActivated(WindowEvent event)
  {
  }

  public void windowDeactivated(WindowEvent event)
  {
  }

  public void windowOpened(WindowEvent event)
  {
  }

  public void windowClosing(WindowEvent event)
  {
    dispose();
    //System.exit(0);
  }
}
0
 

Author Comment

by:bhumi042500
Comment Utility
Sasha

I forgot to mention about MyFrameWithHandling..
It's just a class to class whisc impements WindowListener and is used to close the window

code for MyFrameWithExitHandling is

import java.awt.*;
import java.awt.event.*;

public class MyFrameWithExitHandling extends Frame
  implements WindowListener
{
  public static void main(String[] args)
  {
    Frame f = new MyFrameWithExitHandling("Test Frame");
    f.setSize(200,150);
    f.setVisible(true);
  }

  public MyFrameWithExitHandling(String str)
  {
    super(str);
    addWindowListener(this);
  }

  public MyFrameWithExitHandling()
  {
    super();
    addWindowListener(this);
  }

  public void windowClosed(WindowEvent event)
  {
  }

  public void windowDeiconified(WindowEvent event)
  {
  }

  public void windowIconified(WindowEvent event)
  {
  }

  public void windowActivated(WindowEvent event)
  {
  }

  public void windowDeactivated(WindowEvent event)
  {
  }

  public void windowOpened(WindowEvent event)
  {
  }

  public void windowClosing(WindowEvent event)
  {
    dispose();
    //System.exit(0);
  }
}
0
 

Author Comment

by:bhumi042500
Comment Utility
sasha

My question is not yet answered. Why is the status set to answered??

please correct my code which i posted sometime back
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
Comment Utility
A. The status is set to answered because I have posted an answer to it which you should evaluate and give the appropriate grade when I answer all your questions.
B. I am very happy you decided to write it yourself after all.
C. You should not start the fan in its constructor.
D. To start the fan it is not enough to set stop to false, that will not call the run() method. To start the fan you need to open another Thread and start it just like I did in the start() method of the first comment I posted.
E. You are setting the angle by which the fan will be rotated to (int)(Math.PI/6). Pi/6 is approxx 0.5 so casting it to int will give you 0, meaning that you are not spinning the fan at all. What you need to do is leave it at the double value of Math.PI/6 (for example) and convert from radians to degrees in the method where you paint the fan. After that you can cast it to int.
F. In the paint method you should draw the fan according to the currentAngle variable, otherwise, you are just painting it at the same angle all the time.

Tell me if you have more problems...
Good luck, Sasha.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now