Having a problem with threads and using locks

I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
Withdrawal Threads         Deposit Threads            Balance
Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                Thread 1 deposits $187          $187
                                Thread 3 deposits $169          $356
                                Thread 5 deposits $61           $417
Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
/************Assign2_Main.java************/
import java.util.concurrent.*;
public class Assign2_Main
{//start Assign2_Main
    public static void main(String[] args)
    {//start main
           // create ExecutorService to manage threads
           ExecutorService threadExecutor = Executors.newCachedThreadPool();
        Account account = new SynchronizedThreads();
        Deposit deposit1 = new Deposit(account, "Thread 1");
        Deposit deposit2 = new Deposit(account, "Thread 3");
        Deposit deposit3 = new Deposit(account, "Thread 5");
        Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
        Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
        Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
        Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
        System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
        System.out.println("------------------\t\t---------------\t\t\t-------\n");
        try
            threadExecutor.execute(withdrawal1);       
            threadExecutor.execute(deposit1);     
            threadExecutor.execute(withdrawal2);  
            threadExecutor.execute(deposit2);    
            threadExecutor.execute(withdrawal3);
            threadExecutor.execute(deposit3);       
            threadExecutor.execute(withdrawal4);
        catch ( Exception e )
             e.printStackTrace();
            //shutdown worker threads
           threadExecutor.shutdown();
    }//end main
}//end Assign2_Main/******************Withdrawal.java****************************/
public class Withdrawal implements Runnable
{//start  class Withdrawal
      *constructor
    public Withdrawal(Account money, String n)
         account = money;
         name = n;
    public void run()
    {//start ruin
         int newNum = 0;
            newNum = account.getBalance(name); 
           Thread.yield();
    }//end run
    private Account account;
    private String name;
}//end  class Withdrawal/*******************Deposit.java***************/
import java.util.Random;
public class Deposit implements Runnable
{//start class Deposit
      *constructor
    public Deposit(Account money, String n)
         account = money;
         name = n;
    public void run()
    {//start run
            try
                 Thread.sleep(100);
               account.setBalance(random.nextInt(200), name);
            }// end try
            catch (InterruptedException e)
              e.printStackTrace();
   }//end run
   private Account account;
   private Random random = new Random();
   private String name;
}//end class Deposit/********************Account.java*****************/
*Account interface specifies methods called by Producer and Consumer.
public interface Account
     //place sum into Account
     public void setBalance(int sum, String name);
     //return  value of Account
        public int getBalance(String name);         
} /**************SynchronizedThreads.java****************/
import java.util.concurrent.locks.*;
import java.util.Random;
public class SynchronizedThreads implements Account
{//start SynchronizedThreads
      *place money into buffer
    public void setBalance(int amount, String name)
    {//start setBalance
         // lock object
         myLock.lock();           
        sum += amount;
        System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
           //threads are singnaled to wakeup
        MakeWD.signalAll();
          // unlock object                                                
        myLock.unlock();
       }//end setBalance
        *gets the balance from buffer
       public int getBalance(String name)
    {//start getBalance
         int NewSum = random.nextInt(50);
         //lock object
        myLock.lock();
        try
             if(sum > NewSum)
                 //takes NewSum away from the account
                 sum -= NewSum;
                    System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
            else
                 System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                 //not enough funds so thread waits
                    MakeWD.await();         
            //threads are singnaled to wakeup
            MakeD.signalAll();     
            }//end try
        catch (InterruptedException e)
               e.printStackTrace();
        finally
             //unlock object
             myLock.unlock();
        return NewSum;     
     }//end getBalance
     private Random random = new Random();  
     private Lock myLock = new ReentrantLock();
     private Condition MakeD = myLock.newCondition();
     private Condition MakeWD = myLock.newCondition();
     private int sum = 0;
}//end SynchronizedThreads

You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

Similar Messages

  • 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.

  • I'm having a problem with coreaudiotoolbox and corevideo.dll.

    I'm having a problem with coreaudiotoolbox and corevideo.dll. PC was corrupted, I restored. Now when I launch Safari, I run into errors, can't find these two dll files. Itunes won't download at all because it says something is missing but won't say what. Now what do I do? Apple won't help because they want $50 dollars just to talk with me and I've been down that road before and to no satisfaction. Help please!!

    Taken at face value, you're having trouble with Apple Application Support program files there. (Apple Application Support is where single copies of program files used by multiple different Apple programs are kept, so an AAS problem can affect both iTunes and Safari.)
    Let's try something relatively simple first. Restart the PC. Now head into your Add or Remove programs control panel, select "Apple Application Support", click "Change" and then click Repair.
    If no joy after that, try the more rigorous uninstall/reinstall procedure from the following post (although it's for Vista and 7, just read "Computer" as "My Computer", read "Uninstall a program control panel" as "Add or Remove programs control panel" and assume the system is 32-bit, and you'll be doing the right things):
    Re: I recently updated to vista service pack 2 and I updated to itunes 10.2.1 and ever since I did that my itunes won't open any more.  Itunes starts but before anything loads a window pops up saying that the prograam has encountered a problem and sh...

  • TS5376 I'm having a problem with downloading and installing the new version of itunes for windows (11.1.4)  I have done everything the troubleshooting article has said and it is still not working properly.

    'm having a problem with downloading and installing the new version of itunes for windows (11.1.4)  I have done everything the troubleshooting article has said and it is still not working properly.  I have even done a repair to see if that works and it has not.  Has anyone else found a new way to get it working?

    Try Troubleshooting issues with iTunes for Windows updates.
    tt2

  • Anyone else having a Problem with Leopard and Photoshop CS3?

    I'm using CS3 with Leopard 10.5.4 at work and there are some very aggravating anomalies, that I'd like to nail down to a cause. Most frequently, when switching from apps to P'Shop, the menu bar stays for the previous app, i.e. when going from Finder to P'shop, the menu bar still says Finder and has Finder options. Changing from Lightwave to P'Shop, the menu bar remains Lightwave.
    Occasionally, an Adobe app - P'Shop or InDesign - will simply disappear and not come back. The icon in the dock shows it as active, but no amount of clicking, Command-Tabbing will reveal the app and I have to Force Quit, losing unsaved changes.
    I have a feeling it's Leopard, since, I've used CS3 on Tiger and CS4 on Tiger and never had a problem.
    I'm wondering if upgrading to the latest Leopard would make much of a difference.
    Has anyone come across this and found any kind of answers?
    Thanks for any suggestions.
    -Vincent

    > Just because it doesn't happen to Phil (who may not use all of the same features of the Suite that others do anyway) does NOT mean that these problems are not real and are not mere PEBCAK.
    Right. If someone is having a problem associated with Tiger, it's PEBAK. If Leopard is involved, it's automatically because of Leopard. Apparently, with Apple's latest OS, trouble shooting problems are no longer necessary - just blame it on Leopard and call it a day.
    b FUD
    I find the dynamics here really interesting. This thread would have been very different if Vincent had posted with problems involving Tiger. Would have gone something like this:
    After admonishing him for not providing more information about his setup by posting the obnoxious big blue link on how to ask questions (ahem - we know NOTHING about his machine or configuration, such as which machine, how much RAM, scratch disk or attached peripherals), there'd be all kinds of trouble shooting advice given - "try a new user", "repair permissions", "run DiskWarrior, and on and on ...
    But no, since he mentions Leopard, none of that is apparently necessary and the completely, utterly
    b irresponsible
    advice is given ... "that's just the way Leopard is".
    Those are some serious problems he's reporting that have nothing to do with Leopard. Something is obviously hosed!
    As for discounting my experience because I don't use every app in the suite as extensively as I do Photoshop, I'm FAR more qualified to discuss Leopard and CS issues than Ann or Neil who do not use Leopard at all (and have never used it as far as I know.)
    "Others have problems with it", is their battle cry but it's extremely weak. Do I really need to remind you all that these forum are ALWAYS filled with people who have problems, regardless of version or OS? You act as if this forum was a ghost town when Tiger and CS3 were current!
    Gee, Ann ... people are STILL reporting problems with 10.5 and CS3? How shocking! Guess what - people are STILL reporting problems with 10.4 and CS3 too! Let me make a prediction - people will have problems with 10.8 and CS9!
    Vincent-
    > I don't really deal with fonts anyway ...
    Yes. You do. Even if you never type a single line of text, every application uses fonts to create menus and other GUI items. If one of those fonts are bad, it can create all kinds of problems, including the very problems you mention.
    The fact that you don't seem aware of this and you're still using 10.5.4 leads me to believe you're not familiar with the basic practices of maintaining a healthy system. Again, how did you install Leopard on that machine?
    Look, if you're simply trying to justify using CS4, go right ahead. It's a worthwhile upgrade in it's own right. However, if you install it on that machine in it's current state, CS4 will NOT fix your problems because you do NOT have a healthy system.
    You asked for experiences with Leopard - I can launch every application in both CS3 and CS4 suites
    i simultaneously,
    and STILL not have your issues. I haven't experienced anything like your CS3 problems in Leopard - on both a 2006 Mac Pro and a 2008 Macbook.
    If you'd like help to try and figure out the real problem, I'm more than happy to help. If not, Adobe will gladly take your money ...
    -phil

  • 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 threads and ProgressMonitor

    Dear Friends:
    I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
    But I need deactivate the main class(the main class is the user interface) until the thread ends.
    I use something like this:
    LongTask myTask=new LongTask();
    myTask.start();
    myTask.join();
    Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
    What's wrong?

    Is the dialog a modal dialog? This can block other UI updates.
    In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating

  • Problem with threads and/or memory

    I'm developing an application where there are 3 threads. One of them sends a request to the other, and if the 2nd can't answer it, it sends it to the 3rd (similar to CPU -> CACHE -> MEMORY). When i run the program with 1000-10.000 requests, no problem occurs. When i run it with 300.000-1.000.000 requests, it sometimes hangs. Is this a problem with the garbage collector, or should it be related to the threads mecanism.
    (note: eache thread is in execution using a finite state machine)

    i had been running the program inside Netbeans.
    Running the jar using the command line outside
    Netbeans i have no more problems... Does Netbeans use
    it's own JVM?Depends how you set it up, but look under the options. There are settings for the compiler and jvm that it uses.

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Having some problems with Xcode and C++

    hi guys , I am learning C++ and I am having the following problem when trying to use .h files.
    Example. I make a new document using Xcode2.3.
    in the source folder I got my main.cpp and i 2nd click it, choose add/file/BSD/header file.
    main.cpp
    #include "funtest.h"
    int main ()
    print_num ( 9 );
    return 0;
    funtest.h
    void print_num (int iNum);
    When I compile with Cmd+R , I get:
    [Session started at 2006-06-26 01:59:31 -0400.]
    ZeroLink: unknown symbol '_Z9printnumi'
    complex2 has exited due to signal 6 (SIGABRT).

    Thanks a lot! I don't recommend you to code too early in the morning :P
    The program now looks like this:
    funciones.cpp
    #include "funciones.h"
    #include <iostream>
    int main ()
    print_num ( 9 );
    return 0;
    funciones.h
    /*funciones utilizadas en el programa*/
    #include <iostream.h>
    void print_num (int iNum)
    std::cout << iNum << endl;
    now it builds and prints a fine "9" as output.
    The only thing that is killing me , is in funciones.h, if I don't use #include <iostream.h> the app doesn't run. And if I include it , it runs but Xcode gives me a warning of old headers.
    thanks again.

  • Xfce4: Problems with Sound and Screen Locking on ASUS G53S

    Hello everyone,
    I recently installed Arch for the first time, and decided to use xfce4 for my desktop environment. Everything seems to work well after I followed the instructions given in the wiki, except for the sound and screen-locking functionality. Regarding the sound, I made sure that my user account is added to the audio group, and installed the gstreamer1.0-base-plugins and gstreamer1.0-good-plugins packages. The xfce4-mixer applet starts up without any warnings and recognizes the available devices, but I am still not able to hear any sound. The "Lock Screen" applet simply does nothing upon being clicked. Do you have any ideas as to what I should try in order to fix these problems?
    Thank you very much!

    To be able to lock the screen you have to install and configure a screen locker or screen saver, e.g. xscreensaver, slock, i3lock, maybe combined with  xautolock. When you use a screen locker and not xscreensaver, XFCE might not recognize it. Then create a symlink in /usr/local/bin/xflock4 or use a shellscript if you need to pass parameters.
    My configuration: xautolock with i3lock. /usr/local/bin/xflock4 is this executable shellscript:
    #!/bin/sh
    xautolock -locknow
    xautolock is started in the XFCE autostart with this commandline: xautolock -locker 'i3lock -d -i ~/Bilder/arch/arch-linux-lock.png'
    PS: If you like i3lock and need user switching capabilities, I can give you a patch where Ctrl-S calls a custom command (gdmflexiserver by default)
    Last edited by progandy (2012-06-17 14:19:12)

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Having a problem with drawImage() and dont know why...

    OK, I'm having some problems drawing my image onto the frame.. It will let me draw string, add components, etc.. but as soon as it come to trying to draw an image it just doesn't wanna..
    Here is my code:
    import java.awt.*;
    public class Messenger extends Frame {
         private boolean laidOut = false;
         private TextField words;
        private TextArea messages;
        private Button ip, port, nickname;
        public Messenger() {
             super();
             setLayout(null);
             //set layout font
             setFont(new Font("Helvetica", Font.PLAIN, 14));
             //set application icon
             Image icon =  Toolkit.getDefaultToolkit().getImage("data/dh002.uM");
             setIconImage((icon));
            //add components
            words = new TextField(30);
            add(words);
            messages = new TextArea("", 5, 20, TextArea.SCROLLBARS_VERTICAL_ONLY);
            add(messages);
            ip = new Button("IP Address");
            add(ip);
            port = new Button("Port");
            add(port);
            nickname = new Button("Nickname");
            add(nickname);
        public void paint(Graphics g) {
            if (!laidOut) {
                Insets insets = insets();
                //draw layout
                g.drawImage("data/dh003.uM", 0 + insets.left, 0 + insets.top);
                ip.reshape(5 + insets.left, 80 + insets.top, 100, 20);
                port.reshape(105 + insets.left, 80 + insets.top, 100, 20);
                nickname.reshape(205 + insets.left, 80 + insets.top, 100, 20);
                messages.reshape(5 + insets.left, 100 + insets.top, 485, 300);
                g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top) ;
                words.reshape(5 + insets.left, 440 + insets.top, 485, 20);
                laidOut = true;
        public boolean handleEvent(Event e) {
            if (e.id == Event.WINDOW_DESTROY) {
                System.exit(0);
            return super.handleEvent(e);
        public static void main(String args[]) {
            Messenger window = new Messenger();
            Insets insets = window.insets();
              //init window..
            window.setTitle("Unrivaled Messenger");
            window.resize(500 + insets.left + insets.right,
                          500 + insets.top + insets.bottom);
            window.setBackground(SystemColor.control);
            window.show();
    }Im only new to Java, maybe I've left something out ? Any help will be much appreciated, thanks :)

    Thanks! Got the image to display now... but, next problem.. its a strange one, whenever the application is minimized or has something dragged/popup over the top of it, those sections of text/images disappear... anyone know a reason for this? im using the d.drawImage() like displayed in my code above.. this is the final code for my image..
    Image banner = null;
    try {
         banner = ImageIO.read(new File("data/dh003.uM"));
    } catch(IOException e) { }
    g.drawImage(banner,0 + insets.left, 0 + insets.top, this);and as for my text...
    g.setFont(new Font("Arial",1,14));
    g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top);Thanks in advance!

  • Having a problem with "open" and "import" buttons!

    Hello all,
    I am having some trouble with a basic function in Logic. When I go to "file" and select "import," the window of options appears. However, when I select a file and click the "import" button, literally nothing happens. I have had a similar problem, when I go to the "file" menu and select "open." A window will appear for me to browse to the logic file I want to open, but when I click "open," nothing happens. However, if I manually go to the file and double-click it, then the file will open. The drop-down is set to "All logic document types," though I have tried "all Logic songs" with the same problem. Please help!
    Best,
    Jon

    you know whats funny, this project has to do with arrays of objects and not inheritance. We learned inheritance last week but the lab we are doing which is this, is for arrays of objects. sorry for the confusion lol. so you can completely ignore this, it actually has it in big bold letters at the top of the web page for the lab.

  • Having a problem with iTunes and internet radio. The programme keeps changing stations

    I'm abroad at present and using a wireless connection at the lab. Itunes keeps changing internet radio stations as a function of time,
    Any suggestions or os it a known problem with the current version?
    Don

    Try the following user tip:
    "Invalid drive X:\" install errors

Maybe you are looking for

  • Printing problems with HP OfficeJet G55

    I have a MacBook running OS X 10.5.4 and I'm having problems printing with my HP OfficeJet G55. I have updated to HP Printer Driver 1.1.1, but after updating, I realized my printer type was not in the list. So that did not fix the problem. I connect

  • Purchase Order Creation Query

    Gurus, How do I know if a purchase order is created with reference to a contract and purchase requistion (no RFQ)? Thanks

  • EXEC_SQL connection error

    Hi, I'm trying to use EXEC_SQL to connect to a remote database to copy an image(BLOB) to my form. I've tested the code using dbms_sql access non-BLOB columns from the remote database then adapted those lines to EXEC_SQL to use from a different databa

  • Urgen Help For N958gb Software Update

    Please Helpa me i was updating my n958gb sofware the downnload complate and still 15 minute to update my phone at minute 7 message show to debug or close one of the nokia progeames i'dont remember it and for more than 30 minutes no changes the time l

  • Installing iWork09 without MPN

    I got my mac a few years ago, and used the second registration from my sisters iWork 09 software. Yesterday I had to use the MAC software cd to reset my computer as I had been having some issues. It subsequently wiped my iWork from my drives. I had i