Problem with threads and simulation: please help

please help me figure this out..
i have something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawShapes extends JApplet{
     private JButton choices[];
     private String names[]={"line", "square", "oval"};
     private JPanel buttonPanel;
     private DrawPanel drawingArea;
     private int width=300, height=200;
     public void init(){
          drawingArea=new DrawPanel(width, height);
          choices=new JButton[names.length];
          buttonPanel=new JPanel();
          buttonPanel.setLayout(new GridLayout(1, choices.length));
          ButtonHandler handler=new ButtonHandler();
          for(int i=0; i<choices.length; i++){
               choices=new JButton(names[i]);
               buttonPanel.add(choices[i]);
               choices[i].addActionListener(handler);
          Container c=getContentPane();
          c.add(buttonPanel, BorderLayout.NORTH);
          c.add(drawingArea, BorderLayout.CENTER);
     }//end init
     public void setWidth(int w){
          width=(w>=0 ? w : 300);
     public void setHeight(int h){
          height=(h>=0 ? h : 200);
     /*public static void main(String args[]){
          int width, height;
          if(args.length!=2){
               height=200; width=300;
          else{
                    width=Integer.parseInt(args[0]);
                    height=Integer.parseInt(args[1]);
          JFrame appWindow=new JFrame("An applet running as an application");
          appWindow.addWindowListener(
               new WindowAdapter(){
                    public void windowClosing(WindowEvent e){
                         System.exit(0);
          DrawShapes appObj=new DrawShapes();
          appObj.setWidth(width);
          appObj.setHeight(height);
          appObj.init();          
          appObj.start();
          appWindow.getContentPane().add(appObj);
          appWindow.setSize(width, height);
          appWindow.show();
     }//end main*/
     private class ButtonHandler implements ActionListener{
          public void actionPerformed(ActionEvent e){
               for(int i=0; i<choices.length; i++){
                    if(e.getSource()==choices[i]){
                         drawingArea.setCurrentChoice(i);
                         break;
}//end class DrawShapes
class DrawPanel extends JPanel{
     private int currentChoice=-1;
     private int width=100, height=100;
     public DrawPanel(int w, int h){
          width=(w>=0 ? w : 100);
          height=(h>=0 ? h : 100);
     public void paintComponent(Graphics g){
          super.paintComponent(g);
          switch(currentChoice){
               case 0:     g.drawLine(randomX(), randomY(), randomX(), randomY());
                         break;
               case 1: g.drawRect(randomX(), randomY(), randomX(), randomY());
                         break;
               case 2: g.drawOval(randomX(), randomY(), randomX(), randomY());
                         break;
     public void setCurrentChoice(int c){
          currentChoice=c;
          repaint();          
     private int randomX(){
          return (int) (Math.random()*width);
     private int randomY(){
          return (int) (Math.random()*height);
}//end class drawPanel
That one's from a book. I used that code to start with my applet. Mine calls different merthod from the switch cases. Say I have:
case 0: drawStart(g); break;
public void drawStart(Graphics g){
  /* something here */
drawMain(g);
public void drawMain(graphics g){
g.drawString("test", x, y);
//here's where i'm trying to pause
//i've tried placing Thread.sleep between these lines
g.drawLine(x, y, a, b);
//Thread.sleep here
g.drawRect(x, y, 50, 70);
}I also need to put delays between method calls but I need to synchronize them. Am I doing it all wrong? The application pauses or sleeps but afterwards, it still drew everything all at once. Thanks a lot!

It is. Sorry about that. Just answer any if you want to. I'd appreciate your help. Sorry again if it caused you anything or whatever. .n_n.

Similar Messages

  • Problems with titles and backgrounds PLEASE HELP

    At the beginning of my movie, I have inserted a title (pixie dust) which prompts me to include a background. I have done so. However, when i play the movie in full screen sometimes the title doesn't even show up at other times the title shows but without the pixie dust feature. I have tried to rectify this using precision editor but it doesn't work. When I play the video in the project library the pixie dust feature shows up. Please help. What am I doing wrong?

    This seemed to be a bug in iMovie v.8.0.6. I have the same problem independently of the font and the background but only at the beginning of the project.
    To avoid this problem make a short transition before the title clip and the text will appear in fullscreen mode too.
    Good luck.

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • Firefox is having problems with "Southwest Airlines website" Please help soon

    Whenever I go on Southwest Airline website, it does not work. I am having this problem since last month. Please help on this as soon as you can.

    Clear the cache and the cookies from sites that cause problems.
    * "Clear the Cache": Tools > Options > Advanced > Network > Offline Storage (Cache): "Clear Now"
    * "Remove the Cookies" from sites causing problems: Tools > Options > Privacy > Cookies: "Show Cookies"
    Other things that need your attention:
    Your above posted system details show outdated plugin(s) with known security and stability risks that you should update.
    * Shockwave Flash 10.0 r22
    * Java Plug-in 1.6.0_07 for Netscape Navigator (DLL Helper)
    Update the [[Managing the Flash plugin|Flash]] plugin to the latest version.
    *http://kb.mozillazine.org/Flash
    *http://www.adobe.com/software/flash/about/
    Update the [[Java]] plugin to the latest version.
    *http://kb.mozillazine.org/Java
    *http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform: Download JRE)

  • A Few Questions/Problems With My New iPod *PLEASE HELP*

    Hello! I just received my first iPod (4th Gen, 4GB, Red Nano) two days ago (Christmas Eve) and have so far been fairly happy with it. However, I'm experiencing a few problems with it and am hoping that someone could help me.
    Firstly, a few of the album covers on my iPod are just black squares. I've read other complaints about this on the forums, but haven't seen any solutions. What can I do to fix this?
    Second, I can't figure out how to put my songs in order. On iTunes, it allows me to put songs in alphabetical order, but being that most of my songs are part of full albums, I want my songs to be in the order of when they play on the actual albums. When I try to drag my songs into their correct places, I'm not able to.
    Also, is there any way to delete the games that my iPod came with? I think they might be taking up too much room for my liking...
    OK, well if you can help or add some extra tips to getting started with my iPod, it would be much appreciated. Thank you!

    Bump...

  • Connecting Problems with iPhone and iTunes. Help please?

    When I connect my iPhone 4 to my laptop (Toshiba), I have a huge issue with connecting and syncing my phone on iTunes. During the time it is plugged and attached to my laptop, I can charge it and sync photos that are on my device to the compter, but I can not get it to sync with iTunes. Also, I do not know what my iTunes is fuctioning at (6.1- 7.1- 8.etc), but I did updated it about a month ago. Does anyone have any information and /or/ helpful advice on this topic?
    Thank you!

    Hi CookiCat,
    Follow the troubleshooting steps in the link below:
    http://support.apple.com/kb/TS1538
    Cheers,
    GB

  • Problem with Threads and "plase wait..."-Window

    Hi everyone,
    I have a problem that I'm not able to solve in any way... I have a time-consuming task (a file decryption) which I execute in a separate thread; I've used the SwingWorker class, like suggested by sun-tutorial, and it works right. The problem is that I have to wait that the decryption have finished before continuing with program-execution. Therefore I would like to display a "please wait"-window while the task runs. I've tryed all the possible ways I know but the problem is always the same: the waitWindow is displayed empty, the bounds are painted but the contents no; it's only painted when the decrypt-task has finished. Please help me, I have no more resources....
    decrypt-file code:
    public class DecryptFile {
      private String cryptedFileNameAndPath;
      private ByteArrayInputStream resultStream = null;
      // need for progress
      private int lengthOfTask;
      private int current = -1;
      private String statMessage;
      public DecryptFile(String encZipFileNameAndPath) {
        cryptedFileNameAndPath = encZipFileNameAndPath;
        //Compute length of task...
        // 0 for indeterminate
        lengthOfTask = 0;
      public ByteArrayInputStream getDecryptedInputStream() {
        return this.resultStream;
       * Called from ProgressBarDemo to start the task.
      public void go() {
        current = -1;
        final SwingWorker worker = new SwingWorker() {
          public Object construct() {
            return new ActualTask();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask() {
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent() {
        return current;
      public void stop() {
        current = lengthOfTask;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean done() {
        if (current >= lengthOfTask)
          return true;
        else
          return false;
      public String getMessage() {
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class ActualTask {
        ActualTask () {
          current = -1;
          statMessage = "";
          resultStream = AIUtil.getInputStreamFromEncZip(cryptedFileNameAndPath); //here the decryption happens
          current = 0;
          statMessage = "";
      }The code that calls decryption and displays waitWindow
          final WaitSplash wS = new WaitSplash("Please wait...");
          final DecryptFile cryptedTemplate = new DecryptFile (this.templateFile);
          cryptedTemplate.go();
          while (! cryptedTemplate.done()) {
            try {
              wait();
            } catch (Exception e) { }
          this.templateInputStream = cryptedTemplate.getDecryptedInputStream();
          wS.close();Thanks, thanks, thanks in advance!
    Edoardo

    Maybe you can try setting the priority of the long-running thread to be lower? so that the UI will be more responsive...

  • A problem with the BBM Bold9900 please help me !!

    Hey All , i have a probem with my BBM , when i write something in personal message my conacts can't see what i wrote and when i put my status busy it shows that i'm avaliable, so please i want you to help me !!!!!!!!!!

    Answered in your original thread.
    http://supportforums.blackberry.com/t5/Device-software-for-BlackBerry/a-problem-with-the-BBM/m-p/139...
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with messages and calls,, please respond

    Problem with my iphone is that the messages are sent and received very late, it hangs while sending, when delete a message it takes time to open messages firstly... messages in the thread disappear and such abnormalities.
    and in Calls, i receive notification when the call is missed.
    help!

    I would do a full restore using iTunes (backup first, of course)

  • Problem with adobe acrobat/reader - please help!

    Hello,
    My acrobat reader was fine and I was able to open the pdf files sent to me, then suddenly it just wouldn't open anything at all.  It went into open mode and just stayed there, and wouldn't let me close it.  Then I got a message saying "there is a problem with adobe acrobat/reader.  Please exit and try again".  I've done this lots of times and it still isn't working.
    I would be very grateful for any help or suggestions.  I have windows 7, and as I said its all been fine up until now.
    Thanks.
    mspryce.

    This is the Acrobat forum, not the Reader forum. You should check the reader forum. In the meantime, if you are not running AR9.3 or so, you should update. Prior versions before 9 are not designed for Win7 and that might be your issue -- you gave no indication of version.

  • Problem with serial communicat​ion PLEASE HELP

    Hello everybody !
    I'd like to ask You for some feedback on my wierdo problem that I got with my program.
    I have built a device that detects changes in magnetic field. It is used for detecting vehicles passing it on a highway. Generally the main components communicate with each other by RS-485 protocol, but I would like to connect the device to a PC. To do so I am using a RS-232 protocol (I have a RS485=RS232 hardware converter).
    Now, I made the program (even two), which generally works, BUT some wierd things are going on sometimes; it happens that I have a problem to get a communication (after that, resetting the device by un-powering it helps, sometimes I have to restart the PC as well) but overall it happens quite not so often. The project itself is for passing one of my subject on the university - so I have to run the whole thing over there, here comes another problem : the program did not work on all of the bunch of PC's that are there. Same thing happens on my notebook. The effect of 'non working' is : I am recieving same data packet that is beeing sent... BTW : notebook does not have a RS232 port and I am using a USB-RS232 calbe converter (to count it out from the reason of problems I have checked it on my main PC and it works almost fine - almost because ocasionally I am getting the same sympthomps as I mentioned before ).
    Other problem is, when it works, that I am loosing communication for couple of hundreds of miliseconds and then it comes back to normal (i can see it on the osciloscope).
    I alredy looked for some answears here and there, and I found some suggestions about using 'buffer cleaning method', unfortunatelly I kinda do not know how to do it, and might that help anyways ?
    I also thought about using VISA drivers, but I am having trouble with it as well - the damn thing just does not work.
    My very bling guess is that everyting that I am expierencing is about using the communication protocol and seting it right. I am attaching both of the programs, PLEASE anyone pretty pretty help I totally ran out of ideas and knowledge and day after day I am turning it on and off on my PC and notebook hoping some miracle will occour ... 
    Many many thanks in advance !
      Best regards
                    Tom
    P.S. the program is very unfinished (man things are just put in), the main thing I am struggling now is getting, and setting the communication protocol right.
    Attachments:
    detektor_3_2.vi ‏141 KB

    The biggest problem I see is in the sequence:
    Write out a string.
    Wait 50 mSec.
    Ask how many bytes have been received.
    Read that many bytes.
    Can you guarantee that the data can make a round trip in 50 mSec?
    You should know that the SERIAL PORT WRITE completes NOT when the data has been sent out the port, but when it has been BUFFERED for sending. In other words it returns and starts the timer BEFORE it is actually sent.
    Also, given that there are 232 -> 485 --> USB conversions involved in both directions, I would bet that you are sometimes not allowing enough time for the data to get back.
    If you can control the protocol of what gets sent back, I would change your receiving logic. I think you should check for a carriage return or some other delimiter, and not react until you get that character (or until a reasonable timeout expires).
    In other words, try synchronizing the two ends. Something like:
    N = Get # bytes at port
    Read N bytes from port (flush any characters waiting).
    Write out command string.
    TimeLimit = NOW + 1000 mSec (or whatever)
    S = ''; (Working string)
    repeat
    N = #Bytes at Port
    If N > 0
    S = S + Read N Bytes
    Found = Search String for Delimiter
    until Found or (Now > TimeLimit)
    If Found, parse string S
    You are also re-initializing the port (SERIAL PORT INIT) every time thru the outer loop - that's unnecessary.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Problem with Logic XS Key, PLEASE HELP

    I use my G4 Powerbook laptop for live. I am running most recent version of logic.
    What happens is that Logic will load up fine, but then for no apparent reason logic will come up with an error message saying that the logic key has been removed, but i have not touched it!! I then have to restart logic.
    PLease help i have to get this sorted ASAP cuz i have a gig tomorrow nite. Cheers guys

    Hmm, it does it on both USB ports? And you haven't noticed any problems with other USB gear on those ports?
    When the key is next not recognised by Logic, go into the system profiler and find your USB port that the XS key is on - the XS key will be labelled when it's functioning correctly. Is it still recognised by the computer, or has it gone completely?

  • Problem with simple drawing program - please help!

    Hi,
    I've only just started using Java and would appreciate some help with a drawing tool application I'm currently trying to write.
    The problem is that when the user clicks on a button at the bottom of the frame, they are then supposed to be able to produce a square or circle by simply clicking on the canvas.
    Unfortunately, this is not currently happening.
    Please help!
    The code for both classes is as follows:
    1. DrawToolFrame Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolFrame extends Frame
    implements WindowListener
    DrawToolCanvas myCanvas;
    public DrawToolFrame()
    setTitle("Draw Tool Frame");
    addWindowListener(this);
    Button square, circle;
    Panel myPanel = new Panel();
    square = new Button("square"); square.setActionCommand("square");
    circle = new Button("circle"); circle.setActionCommand("circle");
    myPanel.add(square); myPanel.add(circle);
    add("South", myPanel);
    DrawToolCanvas myCanvas = new DrawToolCanvas();
    add("Center", myCanvas);
    square.addMouseListener(myCanvas);
    circle.addMouseListener(myCanvas);
    public void windowClosing(WindowEvent event) { System.exit(0); }
    public void windowOpened(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowClosed(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    2. DrawToolCanvas Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolCanvas
    extends Canvas
    implements MouseListener, ActionListener {
    String drawType="square";
    Point lastClickPoint=null;
    public void drawComponent(Graphics g) {
    if (lastClickPoint==null) {
    g.drawString("Click canvas first",20,20);
    } else {
    if (drawType.equals("square")) {
    square(g);
    else if (drawType.equals("circle")) {
    circle(g);
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("square"))
    drawType="square";
    else if (event.getActionCommand().equals("circle"))
    drawType="circle";
    repaint();
    public void mouseReleased(MouseEvent e) {
    lastClickPoint=e.getPoint();
    public void square(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void circle(Graphics g) {
    g.setColor(Color.blue);
    g.fillOval(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    Any help would be appreciated!

    Some of the problems:
    1) nothing calls drawComponent(Graphics g)
    2) Paint(Graphics g) has not been overriden
    3) myCanvas is declared twice: once as an instance variable to DrawToolFrame, and once local its constructor. Harmless but distracting.

  • Problem with Desktop Skype freezing, please help

    2 days ago, Dec. 23rd, I started up Skype as usual, but after about a minute, it froze, soon becoming "not responding". I opened Task Manager to try to end it manually, but Task Manager quickly became "not responding" as well, as did Chrome when I opened it when I tried to search for a solution. This had never happened before, and since has only happened when I am trying to use Skype for Desktop. I tried uninstalling and reinstalling multiple times, switching to an older version, and running an antivirus scan to see if a virus might be causing the problem, but none of this helped, and it still freezes itself along with all my other programs, forcing me to restart my computer if I want to be able to use it. I have been using Windows 8 Skype instead today, with no problems, but Skype for Desktop is more convenient for me, and I would very much appreciate it if someone would please help me.
    Also, I don't know if this might be related to the problem, but today I had Task Manager open before starting Skype for Desktop, hoping I could end it before it caused everything to freeze (I couldn't), I was able to see before it froze that Skype was using 100% of my Disk.
    Solved!
    Go to Solution.

    Please,  run the DirectX diagnostics tool.
    Go to Windows Start and in the Run box type dxdiag.exe and press the OK button. This will start the DirectX diagnostics program. Run this diagnostics and save the results to a file. Please, attach this file to your post.
    Be aware that you will have to zip this file before attaching it here.

Maybe you are looking for