Cant get rid of text drawn with drawString, drawString only wrking in paint

Sorry for coming back to ask for more help, but I just caught a snag that I can't get around.
As you can see, "Press Space to start..." is drawn during the paint method. When the user presses space, the other KeyEvents are enabled, but filling a black rectangle where the text is does not hide it. If I put the clearText call before the started = false, then the other KeyEvents aren't enabled.
Also, when I try to draw another string in win method, it doesn't show up.
You can check out the complete applet at http://users.adelphia.net/~uberugh/Race.html
This code compiles with no errors but requires Car.java.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Race extends Applet implements KeyListener {
     private Car car1;
     private Car car2;
     boolean started = false;
     private Image dbImage;
     private Graphics dbg;
     private Graphics txt;
     private Graphics g2;
     Font f = new Font("Arial", Font.PLAIN, 36);
     Font f2 = new Font("Arial", Font.PLAIN, 12);
     public void init() {
          setBackground(Color.black);
          car1 = new Car(10, 146, Color.green);
          car2 = new Car(10, 246, Color.blue);
          addKeyListener(this);
     public void paint(Graphics g) {
          g.setColor(Color.darkGray);
          g.fillRect(0, 0, 600, 100);
          g.fillRect(0, 300, 600, 100);
          g.drawLine(0, 200, 600, 200);
          g.setColor(Color.yellow);
          g.drawLine(550, 100, 550, 300);
          g.setColor(Color.red);
          g.setFont(f2);
          g.drawString("Press Space to start...", 250, 180);
          car1.drawCar(g);
          car2.drawCar(g);
     public void update(Graphics g) {
          if (dbImage == null) {
               dbImage = createImage(this.getSize().width, this.getSize().height);
               dbg = dbImage.getGraphics();
          dbg.setColor(getBackground ());
          dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
          dbg.setColor(getForeground());
          paint(dbg);
          g.drawImage(dbImage, 0, 0, this);
     public void keyTyped(KeyEvent e) {}
     public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {
          int k = e.getKeyCode();
          if (k == KeyEvent.VK_SPACE) {
               started = true;
               clearText(249, 159, 100, 30);
          if (started) {
              if (k == KeyEvent.VK_G) {
                   car1.move();
                   repaint();
                   if (car1.winner) {
                        win(1, txt);
              } else if (k == KeyEvent.VK_RIGHT) {
                   car2.move();
                   repaint();
                   if (car2.winner) {
                        win(2, txt);
     public void win(int x, Graphics g) {
          removeKeyListener(this);
          g.setColor(Color.red);
          g.setFont(f);
          g.drawString(String.valueOf("Player " + x + "wins!") , 200, 218);
          repaint();
     public void clearText(int x, int y, int width, int height) {
          g2.setColor(Color.black);
          g2.fillRect(x, y, width, height);
}

That's because you're trying to paint to a null, non-existent Graphics object.
Your approach is wrong. Don't try to draw when you get the key event, because there may be nothing to draw then anyway (the GUI thread isn't in the act of drawing). Use your event handlers to set internal state of your game object (Race, or other objects as necessary like Car). Then when you draw, use that state. So use your boolean field "started". In your paint method, do this:
if (!started)
     g.drawString("Press Space to start...", 250, 180);Then just get rid of your cleartext method.

Similar Messages

  • Hi, my mac keeps on clicking spontaneously and touchpad hardly works. Cant get rid of it and cant do anything with my mac since it still clicks. Can you help me please?

    Hi, my mac keeps on clicking all the time and the touchpad hardly works. Cant get rid of it. I am not able to do anything with my mac because it just clicks all the time. Can anyone help?

    I am not sure what to do to help sorry but for temporary you could disable your trackpad and use a mouse then atleast your Mac is useable you can fix it

  • I have an app in my app store that is requiring an update but I never purchased the app and when I click update, another apple ID pops up that is not mine.  Now i keep getting reminders to update the app and I cant get rid of it from the app store.  Help.

    I have an app in my app store that is requiring an update but I never purchased the app and when I click update, another apple ID pops up that is not mine.  Now i keep getting reminders to update the app and I cant get rid of it from the app store.  Help.

    You installed a hacked app, originally from the Mac App Store. It contains the receipt for a different app, downloaded using an account that you don't control. You need to identify and remove the hacked app.
    Important: The app you need to remove is not necessarily the one named in the App Store notice. For example, if the App Store says you need to update "Twitter," the hacked app may be "Angry Birds" or something else entirely. Don't make any assumptions about which app you're looking for. To find it, you have to carry out a systematic search.
    Triple-click anywhere in the line of text below on this page to select it:
    kMDItemAppStoreHasReceipt=1
    Copy the selected text to the Clipboard (command-C).
    In the Finder, press the key combination command-F to open a search window, or select
    File ▹ Find
    from the menu bar. In the search window, select
    Search: This Mac
    from the row of tokens below the toolbar. Below that is a popup menu initially showing Kind. From that menu, select  Other...
    A sheet will drop down. In that sheet, select Raw Query and click OK or press return.
    Now there will be a text box to the right of popup menu. Click in that box and paste (command-V).
    The search window will show all the App Store products you've installed. Compare those search results with the list of your purchases from the App Store. To see the complete list, you may need to unhide hidden purchases. If any apps were download from the App Store using other Apple ID accounts that you control, sign in to the store under each of those ID's and check the purchases.
    At least one of the items listed in the search window is not among your purchases in the App Store. Move each such item to the Trash. You may be prompted for your administrator password. Empty the Trash.
    Log out and log back in. Test.

  • How to get rid of text in bookmark toolbar? the default reset will not work

    my bookmark toolbar has changed. I clicked on default reset so just icons show but it will not work. can not get rid of text.

    The Bookmarks Toolbar, by default, shows both icons and text. Here is an Add-on that will allow you to show only the icons.
    *'''''Roomy Bookmarks Toolbar''''': https://addons.mozilla.org/en-US/firefox/addon/roomy-bookmarks-toolbar/
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''
    Not related to your question, but...
    You may need to update some plug-ins. Check your plug-ins and update as necessary:
    *Plug-in check: https://www-trunk.stage.mozilla.com/en-US/plugincheck/
    *Adobe Shockwave for Director Netscape plug-in: [https://support.mozilla.com/en-US/kb/Using%20the%20Shockwave%20plugin%20with%20Firefox#w_installing-shockwave Installing ('''''or Updating''''') the Shockwave plugin with Firefox]
    *Adobe PDF Plug-In For Firefox and Netscape: [https://support.mozilla.com/en-US/kb/Using%20the%20Adobe%20Reader%20plugin%20with%20Firefox#w_installing-and-updating-adobe-reader Installing/Updating Adobe Reader in Firefox]
    *Shockwave Flash (Adobe Flash or Flash): [https://support.mozilla.com/en-US/kb/Managing%20the%20Flash%20plugin#w_updating-flash Updating Flash in Firefox]
    *Next Generation Java Plug-in for Mozilla browsers: [https://support.mozilla.com/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox]

  • Cant get rid of product registration reminder

    it wont go away no matter if you register or say dont remind me again, i've tried uninstalling creative but its still there, and i cant get rid of the bit that i need to!!? is there a way to completely wipe anything to do with creative off your computer in one go, cos currently i can only find the programmes in parts

    Maybe this thread will help.

  • HT2500 CANT GET RID OF GMAIL LABELS ON APPLE MAIL.

    Hi,
    Can somebody please help me.
    I was using Apple Mail with my Gmail for quite some time then I had to use Outlook provided by my workplace. I recently left the job and now back on using Apple mail to manage my gmail.
    I just noticed that there's this weird thing 'labels'. I spent some time going through threads and changed settings few times..... but I cant get rid of this [google mail] underneath my mailboxes which I used to see and use before.
    I dont like to see this  [google mail] thing as it seems a duplication to me.
    And since I dont access usually from gmail via webmail but more often with Apple Mail, I liked how it worked - delete on Apple Mail gets deleted on gmail server.... I just want to use it as it was before.....
    I cant find the way and since theres no contact email for google nor help centre, can someone please please help me? Im attaching screenshots here below...
    I JUST HATE UGLY UNNECESSARY STUFF ON MY LAYOUT¡¡¡¡¡¡¡ in this case - the label...
    Many thanks,
    T

  • Cant get rid of this symbol

    Please can anyone help me.
    I have a symbol on my Blackberry Curve 8520 which I cant get rid off.
    The symbol looks like the Browser symbol but is yellow and there is a number 2 next to it
    I have tried turning the phone off and removing the battery and still the symbol is there.
    It also seems to be draining my battery very quickly.
    Does anyone have any ideas.
    Solved!
    Go to Solution.

    kstrong wrote:
    Hi Jacqui,
    Thank you so much for your help it has been driving me mad and no one I spoke to had the answer either. Where on earth did you find the answer?
    Kelly
    it is written in the manual that was shipped with your device.
    The search box on top-right of this page is your true friend, and the public Knowledge Base too:

  • In finder under shared there is a home pc i dont recognize, is it dangerous i cant get rid of it?

    in finder under shared there is a home pc i dont recognize, is it dangerous i cant get rid of it?

    so i have tried so very hard to make sure this wouldnt happen. i have a time capsule that only i use... and my family has a router that they use with a different network name. though i am bridging through that network it is a hidden network i use. now ill check to see if this is my moms comp but my computer has freaked me out with odd things happening for about since january when i got it.. so i mean i just dont know what to do anymore. trust me ive stayed up all night i even called road runner to try and get some advuce and they r useless. so yeah. whatevs.

  • Very big icons on my screen.  Have turned off and on.  Cant get rid off.  Cant downsize screen to enter my pin.  Sems blocked or stalled.  What to do?

    Very big icons on my screen.  Have turned off and on.  Cant get rid off.  Cant downsize screen to enter my pin.  Sems blocked or stalled.  What to do?

    Double tap with THREE fingers to turn zoom off. Then go into Settings>General>Accessibility and turn zoom off for good.

  • A message has popped  up in safari saying we have won a prize cant get rid of it

    a message has popped  up in safari saying we have won a prize cant get rid of it

    Try a reset : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot.
    Then when the iPad has restarted clear Safari's cache : Settings > Safari > Clear Cookies And Data (Clear Cache on iOS 4) and also Clear History
    You could also close Safari completely and then re-open it : from the home screen (i.e. not with Safari 'open' on-screen) double-click the home button to bring up the taskbar, then press and hold any of the apps on the taskbar for a couple of seconds or so until they start shaking, then press the '-' in the top left of the Safari app to close it, and touch any part of the screen above the taskbar so as to stop the shaking and close the taskbar.

  • I dont know all of sudden firefox search engine changed from google to my search and i cant get rid of that

    all of sudden a new search engine started in place of google and i cant get rid of that even i uninstalled and reinstalled many times but that problem still there,seem to be some some type of bug in latest firefox .

    Hi naveen,
    You should take a look at the Knowledge Base article [[Search bar]]. Your default search might have been changed by a particular site. Sites like MSN, Yahoo, etc have been know to ask to become your homepage and change your search engine.
    If the address bar search has been changed as well, you might want to take a look at [[Location bar search]].
    If that doesn't work you should look at the article [[Preferences are not saved]]. We've also got a [https://support.mozilla.org/en-US/kb/removing-babylon-searchqu-or-mystart list of common search related issues] that might be helpful.
    Finally, your issue may be because you've been hit with some [https://support.mozilla.org/en-US/kb/Is%20my%20Firefox%20problem%20a%20result%20of%20malware?s=malware&r=0&e=sph&as=s#w_how-do-i-get-rid-of-malware Malware].
    Hopefully this helps!

  • How do I get rid of "Server responded with an error"?

    How do I get rid of "Server responded with an error" in Calendar?  Calendar is frozen and Calendar menu will not allow preferences or quit.

    Please take each of the following steps that you haven't already tried, until the problem is resolved. Back up all databefore making any changes.
    Step 1
    From the Calendar menu bar, select
    Calendar ▹ Preferences ▹ Accounts
    Choose the affected account from the list on the left and uncheck the box marked
    Enable this account
    Then check the box again. Test.
    Step 2
    Make a note of the account settings, then delete the account and add it back with the same settings.
    Step 3
    If you can't add the account, the settings may be invalid. Verify them. How you do that depends on what kind of account it is. If it's a Google calendar and you've activated 2-step verification, you need to generate an application-specific password in your Google account and enter it in place of your old password.
    Step 4
    Quit Calendar. Triple-click the line below on this page to select it:  
    ~/Library/Calendars/Calendar Cache  
    Right-click or control-click the highlighted line and select
    Services ▹ Reveal
    from the contextual menu.* A Finder window should open with a file named "Calendar Cache" selected.
    Move the selected file to the Trash. There may be one or two other files in the same folder with names that begin in "Calendar Cache". If so, delete those files too.
    *If you don't see the contextual menu item, copy the selected text to the Clipboard (command-C). In the Finder, select
    Go ▹ Go to Folder...
    from the menu bar, paste into the box that opens (command-V). You won't see what you pasted because a line break is included. Press return.

  • Cant get rid of repeating future events. How to get rid of these and not have forever!! ??

    Cant get rid of repeating future events.  I deleted the calendar with these events but now I still have these "ghost" events showing up!! How to get rid of these and not have forever!! Really irritating, wont use repeat events ever again!! Have this problem on iphone and ipad even though deleted calendar from both!! Which BTW deleted my email connected with it too which was really irritating.

    Marisalynne wrote:
    I have the applications folder in my harddrive and then the one that I moved to my desktop when I first got my computer.
    Where was the one that you moved to your desktop before you moved it to the desktop?
    I really don't understand what you're trying to say. If I have a folder in A, and I move it to B, then the folder will be in B. There is no duplication. I still have only one folder, only the location is different.
    Furthermore, your desktop is on your hard drive. Everything is on your hard drive.

  • Cant get data from text file to print into Jtable

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest

    Here's a thread that loads a text file into a JTable:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172
    And my reply in this thread shows how you can use a text file as a simple database:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=342380

  • I call a class using a Button but i cant get rid of the old page??

    Hey,
    I cant get rid off the current page when i want to go to the next page! this.dispose(); doesnt work because the class doesnt implement ActionListener!! This is the code that i have used:
    JButton back = new JButton("BACK");
            back.addActionListener(new ActionListener()       
                  public void actionPerformed(ActionEvent e)           
                       VowelmSound s = new VowelmSound();
                        s.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                        s.show();
                        //this.dispose();           
             });         });       and this is the code for main
    public static void main(String[] args)
    {JFrame draw = new punjabidraw();   
             draw.setVisible(true);  
    }so was wondering if there was another method i could use to get rid of the old page?? repaint maybe???
    Hope you can help
    Kind Regards
    RSH

    //this.dispose(); 'This' is a nameless ActionListener object. Can't be dispose()ed.
    What do you want to dispose() really?
    And, what is your punjabidraw class?
    Save the currend page reference in a variable called, say, curPage, then do
    curPage.dispose();in the event handler for the button.

Maybe you are looking for