Can't do paint computation only outside EDT

Hello, I am really sorry, this must be obvious, but I just can't do myself, or find on the web, an example of doing paintComponent() "the proper way". That is, if I have a lot of computation of the image, before the actual painting occurs, I should first get out of EDT, do this outside, and then come back with invokeLater(). That is what I read in the docs and on the web - please correct me if I am misunderstanding something. Under java 1.4.2 (most browsers still run that, so I have to use it for applet development), there is no SwingWorker, so I thought I would just spawn a thread. But the following code fails to paint anything - if I resize the window, I expect the diagonal to appear. This is what happens if I just put g.drawLine(x0, y0, x1, y1); directly inside paintComponent(). But to do it the right way, as if in a computational intensive situation, does not work. What mistake am I making? Here is the isolated faulty code:
import javax.swing.*;
import java.awt.*;
public class Foobar
     public static void main(String[] args)
          JFrame frame = new JFrame();
          FoobarPanel panel = new FoobarPanel();
          frame.setContentPane(panel);
          frame.pack();
          frame.setVisible(true);
class FoobarPanel extends JPanel
     public void paintComponent(final Graphics g)
          new Thread(new Runnable()
               public void run()
                    paintOutsideEDT(g);
          }).run();
     void paintOutsideEDT(final Graphics g)
          final int x0 = 0;
          final int y0 = 0;
          Dimension d = getSize();
          final int x1 = d.width - 1;
          final int y1 = d.height - 1;
          SwingUtilities.invokeLater(new Runnable()
               public void run()
                    paintBackInEDT(g, x0, y0, x1, y1);
     void paintBackInEDT(Graphics g, int x0, int y0, int x1, int y1)
          g.drawLine(x0, y0, x1, y1);
}

Here's an example that draws random ellipses on a JPanel using a background thread. The time-intensive processing is mimicked by a call to Thread.sleep(...):
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.SwingWorker;
public class BackgroundPaint
  private static final int SIDE = 400;
  private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
  protected static final long SLEEP_DELAY = 500;
  private Random random = new Random();
  private List<EllipseColor> ellipseColorList = new ArrayList<EllipseColor>();
  //private SwingWorker<Void, Void> swingworker;
  private JPanel mainPanel = new JPanel()
    @Override
    protected void paintComponent(Graphics g)
      super.paintComponent(g);
      myPaint(g);
  public BackgroundPaint()
    mainPanel.setPreferredSize(APP_SIZE);
    new Thread(new Runnable()
      public void run()
        while (true) // lord I hate this
          try
            Thread.sleep(SLEEP_DELAY);
          catch (InterruptedException e){}
          Color c = new Color(
              random.nextInt(256),
              random.nextInt(256),
              random.nextInt(256));
          int centerX = random.nextInt(SIDE);
          int centerY = random.nextInt(SIDE);
          int radiusX = random.nextInt(Math.min(Math.abs(SIDE - centerX), centerX));
          int radiusY = random.nextInt(Math.min(Math.abs(SIDE - centerY), centerY));
          Ellipse2D ellipse = new Ellipse2D.Double(
              centerX - radiusX, centerY - radiusY,
              2*radiusX, 2*radiusY);
          ellipseColorList.add(new EllipseColor(ellipse, c));
          mainPanel.repaint();
    }).start();
  private void myPaint(Graphics g)
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(4));
    g2.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    for (EllipseColor ec : ellipseColorList)
      g2.setColor(ec.getColor());
      g2.draw(ec.getEllipse());
  public JComponent getComponent()
    return mainPanel;
  private class EllipseColor
    private Ellipse2D ellipse;
    private Color color;
    public EllipseColor(Ellipse2D ellipse, Color color)
      this.ellipse = ellipse;
      this.color = color;
    public Ellipse2D getEllipse()
      return ellipse;
    public Color getColor()
      return color;
  private static void createAndShowUI()
    JFrame frame = new JFrame("BackgroundPaint");
    frame.getContentPane().add(new BackgroundPaint().getComponent());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  public static void main(String[] args)
    java.awt.EventQueue.invokeLater(new Runnable()
      public void run()
        createAndShowUI();
}Edited by: Encephalopathic on Nov 23, 2008 8:30 AM

Similar Messages

  • How can I make my computer only recognize my network and not that of one of my neighbors?

    How can I make my computer only recognize my network and not that of one of my neighbors? This is for when I am at home, and everytime the computer goes to sleep it essentially loses the connection, only to pick up my neighbors network when it is awaken.
    I am on Comcast (Xfinity) Highspeed Cable wireless modem/router
    Thanks in advance!
    Mark

    You can make your network the preferred network.
     > System Preferences... > Network > Advanced... > Drag your preferred network name to the top of the list.

  • IPhone contacts: file transfer to Windows 7 via USB-cable  My iPhone can communicate with the computer only via USB-cable (no mobile data, no bluetooth, no internet, no outlook). As I want to get the phone to the "doctor" I want to save specifically

    iPhone contacts: file transfer to Windows 7 via USB-cable
    My iPhone can communicate with the computer only via USB-cable (no mobile data, no bluetooth, no internet, no outlook). As I want to get the phone to the "doctor" I want to save specifically my contact data and calendar details on the computer (OS: Windows 7). How can I solve this task? I will appreciate your valuable information, thanks.

    Using the iPhone, the USB cable, iTunes and Windows Contacts, sync the iPhone contacts to Windows Contacts. That will save them there. They are also included in the iPhone backup made in iTunes, and if you use iCloud.
    I'm sorry, I missed the calendar part the first time I looked. For calendar, you need a supported application on the computer (Outlook) or if you use iCloud, you can use the iCloud contacts and calendar app to sync.

  • HT1414 I can not sync my iPhone after restoring it - my computer only gives me the restore (again and again and again) option.  I have no music and only a few aps now on my iPhone.  Any tips before I go to the genius bar?

    I can not sync my iPhone after restoring it - my computer only gives me the restore (again and again and again) option.  I have no music and only a few aps now on my iPhone.  Any tips before I go to the genius bar?

    If you restored as new, without using a backup, and still only get an option to restore, there is a hardware problem or the phone was previously hacked (jailbroken, downgraded iOS, unauthorized unlock).  Your only option is to take it to Apple or whoever provides iPhone service in your country.

  • How can i remote a computer outside of my nextwork and has a dynamic IP

    How can i remote a computer outside of my nextwork and has a dynamic IP.
    I have have mac set up overseas and will need to remote access it from time to time, but the mac has a dynamic IP, is there anyway around for me to access IT.
    Have been using "log me in" but its too slow.
    Thanks in advance for any assistance

    The subject of connecting ARD via the Internet has been covered here many times already (search the forum for "Internet"), but take a look at this web page:
    http://www.starklmc.com/ard.htm
    It should help, though you may have to refer to your router's documentation for specifics on opening and forward ports in that particular unit.
    To get a "static IP" use a service like dyndns.com

  • I can turn my phone on only when connected to power. however it cant pick up signal it says connect to apple/support but I cant plug in to computer as it needs power I think the battery aerial is stuffed can I still backup phone if i put into get repaired

    can turn my phone on  only when plugged into the power. everything is still accessable on the when when this is done. but it cant pick up a signal its just serching.
    a message says i need to connect to apple/support but i can plug into the computer as its not getting any power and i cant turn on.
    I need pictures and stuff baked up on it as i dont want to loose them.
    I think the battery/aerial in stuffed as it go some water on it.
    will it be possible to save the data when getting repaired???

    Hello there stidhambr15,
    I was researching the issue you are having and recommend a couple of things. First it might be a good idea to reset the device following iPhone, iPad, iPod touch: Turning off and on (restarting) and resetting found here http://support.apple.com/kb/ht1430
    Resetting your device
    Press and hold the Sleep/Wake button and the Home button together for at least ten seconds, until the Apple logo appears.
    If that doesn't quite get the device going again, I recommend restoring the device.
    iTunes: Restoring iOS software
    http://support.apple.com/kb/ht1414
    Might even be a good idea to turn off the phone, reseat the SIM card, and turn it back on.
    iPhone and iPad: How to remove the SIM card
    http://support.apple.com/kb/ht5163
    iPhone 4 (GSM model)
    iPhone 4S
    Cheers,
    Sterling

  • HT1386 my Ipod will not connect to my computer it worked yesterday but not today and it is only a new ipod touch, it will not even be recognised on my itunes but yet it can charge off my computer. need help!

    it worked yesterday but not today and it is only a new ipod touch, it will not even be recognised on my itunes but yet it can charge off my computer. need help!

    iOS: Device not recognized in iTunes for Mac OS X
    or
    iOS: Device not recognized in iTunes for Windows

  • I partitioned a small drive for a windows program, and now the computer only wants to boot to Windows.  How do I get back to Mac so I can have a choice of drives?

      I partitioned a small drive for a windows program, and now the computer only wants to boot to Windows.  How do I get back to Mac so I can have a choice of drives?

    That doesn't sound good. It sounds like the power outage might have corrupted the partition for OS X. I would suggest booting from the Install DVD that came with your Mac while holding down the C key. Once you have selected the language start up Disk Utility from the pull down menu and repair the disk. Once you have done that then repair permissions also.
    Allan

  • I have a brand new mini mac and a new apple TV. Both have been updated and can see my movies in itunes. I can use Netflix and stream music. I have tried to use my old laptop and it streams video fine. But my new computer only see a spinning circle.

    I have a brand new mini mac and a new apple TV. Both have been updated and can see my movies in itunes. I can use Netflix and stream music. I have tried to use my old laptop and it streams video fine. But my new computer only see a spinning circle.

    Please read this whole message before doing anything.
    This procedure is a diagnostic test. It won’t solve your problem. Don’t be disappointed when you find that nothing has changed after you complete it.
    The purpose of this test is to determine whether the problem is localized to your user account. Enable guest logins* and log in as Guest. Don't use the Safari-only “Guest User” login created by “Find My Mac.”
    While logged in as Guest, you won’t have access to any of your personal files or settings. Applications will behave as if you were running them for the first time. Don’t be alarmed by this; it’s normal. If you need any passwords or other personal data in order to complete the test, memorize, print, or write them down before you begin.
    Test while logged in as Guest. Same problem?
    After testing, log out of the guest account and, in your own account, disable it if you wish. Any files you created in the guest account will be deleted automatically when you log out of it.
    *Note: If you’ve activated “Find My Mac” or FileVault in OS X 10.7 or later, then you can’t enable the Guest account. The "Guest User" login created by "Find My Mac" is not the same. Create a new account in which to test, and delete it, including its home folder, after testing.

  • HT1689 the computer I orginally sync"ed" to broke.  The new computer only has about a dozen songs.  How can I downdload my music from the Ipod to the computer?

    the computer I orginally syncd to broke.  The new computer only has about a dozen songs that were purchased from itunes.  Is there any way
    I can get the thousands of other songs from the ipod downloaded to the computer.

    - Connect the iPod to the computer and transfer iTunes purchases:
    iTunes Store: Transferring purchases from your iOS device or iPod to a computer
    - Transfer other music by using a third-party program like one of those discussed here:
    Copy music
    - Connect the iPod to the computer and make a backup by right clicking on the iPod under Devices in iTunes and select Back Up
    - Restore the iPod from that backup
    Note that the iPod backup that iTunes makes does not included synced media like apps and music.

  • Can i get the time capsule to automatically back up my file from my Mac Book Air but have certain files which are only stored on the time capsule and not the computer? Then can i access these files only on the time capsule without connecting it?

    Can i get the time capsule to automatically back up my file from my Mac Book Air but have certain files which are only stored on the time capsule and not the computer? Then can i access these files only on the time capsule without connecting it?

    igonneau wrote:
    Can i get the time capsule to automatically back up my file from my Mac Book Air but have certain files which are only stored on the time capsule and not the computer?
    You can, but how are you going to back up those other files?  When (not if) your Time Capsule fails, you risk losing them.  See #Q3 in Using Time Machine with a Time Capsule for details.
    Then can i access these files only on the time capsule without connecting it?
    Not sure what you mean.  You have to connect a computer, either via Ethernet cable or wirelessly, to read or write to the disk. 

  • Can't install OSX Mountain Lion, on the disk selection screen i cant select the Macintosh HD to install OSX giving a message (This disk cannot be used to start up your computer).only have one disk to select and my partition map scheme is GUID partition

    just bough OSX Mountain Lion, my laptop operating with v10.6.8.  Can't install OSX Mountain Lion, on the disk selection screen i cant select the Macintosh HD to install OSX giving a message (This disk cannot be used to start up your computer).only have one disk to select and my partition map scheme is GUID partition table. 24.44gb disk available.

    Verify your computer can run Mountain Lion:
    Upgrading to Mountain Lion
    To upgrade to Mountain Lion you must have Snow Leopard 10.6.8 or Lion installed. Purchase and download Mountain Lion from the App Store. Sign in using your Apple ID. Mountain Lion is $19.99 plus tax. The file is quite large, over 4 GBs, so allow some time to download. It would be preferable to use Ethernet because it is nearly four times faster than wireless.
         OS X Mountain Lion - System Requirements
           Macs that can be upgraded to OS X Mountain Lion
             1. iMac (Mid 2007 or newer) - Model Identifier 7,1 or later
             2. MacBook (Late 2008 Aluminum, or Early 2009 or newer) - Model Identifier 5,1 or later
             3. MacBook Pro (Mid/Late 2007 or newer) - Model Identifier 3,1 or later
             4. MacBook Air (Late 2008 or newer) - Model Identifier 2,1 or later
             5. Mac mini (Early 2009 or newer) - Model Identifier 3,1 or later
             6. Mac Pro (Early 2008 or newer) - Model Identifier 3,1 or later
             7. Xserve (Early 2009) - Model Identifier 3,1 or later
    To find the model identifier open System Profiler in the Utilities folder. It's displayed in the panel on the right.
    Open Disk Utility and verify the drive is partitioned using GUID and formatted Mac OS Extended, Journaled. If it is then do this:
    Repair the Hard Drive and Permissions
    Boot from your Snow Leopard Installer disc. After the installer loads select your language and click on the Continue button. When the menu bar appears select Disk Utility from the Utilities menu. After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported click on the Repair Permissions button. Wait until the operation completes, then quit DU and return to the installer.
    If DU reports errors it cannot fix, then you will need Disk Warrior and/or Tech Tool Pro to repair the drive. If you don't have either of them or if neither of them can fix the drive, then you will need to reformat the drive and reinstall OS X.
    Now try installing Mountain Lion.

  • I think my apple computer only recognises my iphone 4 as a camera. How can I fix this please? T

    I hope some one can help me...I am trying to follow the process of unlocking my iphone4 for overseas travel. It has been done with my provider but I am having trouble accessing itunes to complete the task as I think my computer only recognises my phone as a camera. My prtner has an iphone3 on the same computer and this could be part of the problem.

    See http://support.apple.com/kb/TS1538 for troubleshooting steps.  (Another iPhone on the same computer wouldn't cause issues with your phone not being detected in iTunes.)

  • Can anyone get personal information from my computer from outside the home

    Hello, Is it possible for someone to get information from my computer from outside the house
    ? thanks

    Sadly your credit card info is easy to pickup from the following insecure methods:
    1. Connecting to a passwordless WiFi, or one with just WEP or WPA version 1 encryption.  Always use WPA2. Make sure your password is not in any dictionary of any language.
    2. Delete all browser cookies for retailers that have had credit card transactions before using the computer in a WiFi hotspot that has no password requirements.
    3. Connecting to a website without at least 128 bit RSA key encryption and entering your credit card number in such a website.  Browsers have a method of determining your encryption either by clicking the lock icon, or hovering over the lock icon, or viewing the web browser security settings.  When making online transactions, do not save your credit card number to any website, and secure the website you are making a transaction with, with a password that isn't found in any dictionary.
    4. Look at your credit card receipts wherever you use your credit card.  Both the customer copy and the retailer copy should have all but the last 4 digits Xed out.  If they are all visible, inform the retailer there are more secure credit card machines that do, and you won't purchase anything with them by credit card until they use such machines.
    5. Gas stations, it is better that your receipt is not printed at all, and if it is, don't forget to check with the attendent if they have a copy of the receipt and get it from them.
    6. Credit card wireless scanners.  Apparently people have managed to scan other people's back pockets and get the credit card number off them.  If at all possible don't leave your credit card in your back pocket, and use your front pocket, or a purse that you always keep an eye on.
    If your bill online or otherwise indicate charges you don't recognize, get your number changed immediately, and dispute the charges within 60 days.  If you don't you may be liable for them.  Otherwise you are usually only liable for the first $50.

  • Hi i took my wifes phone and backed up on her computer , then i deleted everything from her phone and made restore from my laptop (my old phone ) , now I want to restore wifes phone back but on her itunes can't see her backup (only see mine). please help

    hi i took my wifes phone and backed up on her computer , then i deleted everything from her phone and made restore from my laptop (my old phone ) , now I want to restore wifes phone back but on her itunes can't see her backup (only see mine). please help

    Thanks for responding but the link seems to be relevant to Windows. Is there a similar method for Android phones?

Maybe you are looking for

  • Analog Signal to Digital a Primer

    Many users have analog material sitting around, and they would like to get it into digital form, so that it can be edited. As this material is below SD (Standard Definition) quality, I will address the methods for digitizing it, so that it can be bes

  • How do I install iMovie '06 on my iMac?

    I have the original iLife '06 and am having a problem installing iMovie '06 on my iMac 3.06, 2GB, running Mac OSX 10.5.8. I thought I had installed it, but when I booted it, this message popped up. "You cannot open the application "iMovie HD" because

  • Wacom Cintiq tool problems with illustrator CC 2014

    This is the first time I have ever posted in a forum. I am having the weirdest issue with my Wacom Cintiq 12wx and Illustrator. It seems to work fine with every other Adobe program I use but I need it most for illustrator. Description of the issue: W

  • How do I turn off automatic bookmark creation when combining multiple PDFs into one?

    When I combine multiple PDFs into one, I need Adobe to use the CUSTOM bookmarks I created in the original PDFs. I do NOT want the additional PDF name as a bookmark in this instance. Is there a way to turn this option OFF in Acrobat Professional? I ha

  • Upgrading to tiger w. classic 9

    now that i know 10.4 will also run classic 9 i am considering upgrading. 9.2.2 is critical for all my business accounting software, so i am obviously concerned i do it right. when i upgrade to 10.4 do i need to do anything with 9.2.2 already installe