Forcing repaints in J2SE

Is there a way to force immediate repaints on a J2SE Canvas as in the MIDP method Canvas.serviceRepaints()?

MIDP's Canvas.serviceRepaints() forces any pending requests for repaint()s.
In J2SE, closest is update() which is what's called if there is a pending repaint().
You can do this in J2SE:
canvas // is your Canvas
canvas.update(canvas.getGraphics());

Similar Messages

  • Force repaint with Double-buffering

    i've been using the "classic" DB class you can find everywhere on the net (just extend a component - JPanel in my case - keep an image and draw the image to component on repaint ) the class works well however when the code execution is intense the repaint manager doesnt have time to draw the image to the screen- i've tried playing to the repaintManger but in fact it seems like i can control very little of it. Is there a way to force repainting to screen? thanks

    If "the code execution is intense", then the code should be running in a separate thread so that it doesn't block up the painting.

  • Forcing Messages to be processed

    Hi Everybody,
    :. I need to process all pending messages before doing some task. Is there a way to process every message in the Event queue? Is there a flushMessages method or alike?
    Regards.
    kilsw5

    :. I bought a Java component that communicate to serial devices. The problem is that that component use Sleep method to wait for their answers, causing the whole GUI to freeze. No way to modify the component itself, so I was thinking to force repainting the whole app before calling any method of that component. I just want a simple synchronization, a way of flushing the AWT event queue. That would solve most of the problem.
    Regards.
    kilsw5

  • TileLayout fails to repaint after swapping dataProvider

    I have a TileLayout on a List with a dataProvider rendering images for me through an itemRenderer.
    I have multiple collections that I'm using on the same list and swapping them out via a button.
    When I do the swap the layout incorrectly updates the display and only shows me the previous height if there was no scroll bar (ie if View 1 has 40 elements and is 4 elements wide and View 2 has 4 elements, when switching from view 2 to view 1 I would only see 4 elements again)
    I tried to update the display by setting the layout again:
    listObj.layout = new TileLayout();
    and this seemed to work. But I was getting some broken images displaying when switching the view. So I added a clear call to the swap:
    listObj.dataProvider.RemoveAll();
    and now I'm back where I started and the view wont update.
    Since there's no force repaint in flash I can't update the view correctly and am stuck.
    Please help,
    Thanks.

    like this?
                   if (objList.dataProvider != null)
                        var data:ListCollectionView = ListCollectionView(objList.dataProvider);
                        data.refresh();

  • Repaint question on j2me midp 2.0

    Hi,
    Is there a way to force repaint() happens at the time you want to call it instead of queueing it in an event queue? If I do that, what are the drawbacks?
    And on a real phone, what is the performance difference before repaint() a region verus repaint() the whole screen? And does setting up clipping rect help performance?
    Thank you.

    I think that you can call repaint() whenever you want in GameCanvas. The good thing is that you have the full control. The bad thing is that you will see the screen "flashing" if you call repaint() too frequently.
    The performance is dependent on the MIDP 2.0 implementation of the phone. MIDP 2.0-compatible phones might have different performance but they must have the same functionality.
    I have tried on Motorola V300 and V600, repainting on the clipped region is faster than repainting the whole screen.

  • Safari 4 Color and Gamma STILL Washes Out -- NOT Solved 7/4/2009

    OK, just bringing this back to the top:
    http://discussions.apple.com/thread.jspa?threadID=2032159&start=0&tstart=0 is listed as 'Solved', but that was totally premature. The alleged fixes range from the usual repair permissions, trash Safari prefs, reboot, etc., but it's all temporary, at best.
    A CLEAN install of the OS to a virgin partition, followed by permissions, repair, combo updater, apply all related Safari, repair permissions, delete, shutdown and reboot leaves you with the same issue as soon as you sleep displays, go to screen saver, use FUS, and come back in with Safari 4 already running, you will get the screen wash as further described here:
    http://gallery.me.com/frederico/100070
    Posted Elsewhere:
    Gamma settings within Safari 4 windows since upgrade will "degrade" (read: darken and stratify) when scrolling the window contents, using either scroll wheel, arrow keys, or mouse on scroll bar. Text also becomes progressively fuzzy and its opacity decreases until the entire window is black.
    Moving another application window in front, or minimizing and maximizing the errant window, moving or resizing it in any manner, or using the 'Force Repaint' command will restore the appearance immediately. I can capture screenshots of it, but cannot use your included screenshot command, as the mere act of dropping down the report slider forces repaint.
    Quitting Safari, rebooting machine, or just logging out will "cure" the problem for a short time, but it returns fairly quickly. I do not believe I have any third party plugins causing the issue; I removed several and the problem still crept back; each user account, including a freshly created test account sees this error.
    This can fairly regularly be triggered by sleeping the displays or entering locked screensaver, logging in, and going to several sites such as Daring Fireball, Mac OS X Hints, and anything displaying PNG and Flash combos.
    Perhaps related: I updated to 10.5.7 at the same time, and when I restarted, noticed that the gamma profile on my center screen (of five LCDs) was severely washed out. Switching back and forth between any other color profile in Displays and back to my calibrated profile will cure the wash -- until I log out and back in. Each user account, including a freshly created test account sees this error.
    Have also clean installed OS X 10.5.4 and updated to a10.5.7 using combo updater; then installed and updated Safari 4. Problem follows Main screen (menubar host) on each of five LCD displays on three ATi video cards on Mac Pro Quad 2008.
    Getting ready to restore back to Safari 3 and 10.5.6 from clone; this behavior is becoming tedious.
    Screenshots and additional details on request; <Edited by Host>
    http://gallery.me.com/frederico/100070
    More info and more users seeing the same thing here
    http://www.macosxhints.com/article.php?story=2009062403534417
    http://www.macosxhints.com/article.php?story=2009062403534417#comments
    Hardware Overview:
    Model Name: Mac Pro
    Model Identifier: MacPro3,1
    Processor Name: Quad-Core Intel Xeon
    Processor Speed: 2.8 GHz
    Number Of Processors: 2
    Total Number Of Cores: 8
    L2 Cache (per processor): 12 MB
    Memory: 6 GB
    Bus Speed: 1.6 GHz
    Boot ROM Version: MP31.006C.B05
    System Version: Mac OS X 10.5.7 (9J61)
    Kernel Version: Darwin 9.7.0
    Boot Volume: system
    Boot Mode: Normal
    ATI Radeon HD 2600 XT:
    Chipset Model: ATI Radeon HD 2600
    Type: Display
    Bus: PCIe
    Slot: Slot-1
    PCIe Lane Width: x16
    VRAM (Total): 256 MB
    Vendor: ATI (0x1002)
    Device ID: 0x9588
    Revision ID: 0x0000
    ROM Revision: 113-B1480A-252
    EFI Driver Version: 01.00.252
    Displays:
    CMC 22 W:
    Resolution: 1680 x 1050 @ 60 Hz
    Depth: 32-Bit Color
    Core Image: Hardware Accelerated
    Mirror: Off
    Online: Yes
    Quartz Extreme: Supported
    Rotation: Supported
    CMC 22 W:
    Resolution: 1680 x 1050 @ 60 Hz
    Depth: 32-Bit Color
    Core Image: Hardware Accelerated
    Main Display: Yes
    Mirror: Off
    Online: Yes
    Quartz Extreme: Supported
    Rotation: Supported
    ATI Radeon HD 2600 XT:
    Chipset Model: ATI Radeon HD 2600
    Type: Display
    Bus: PCIe
    Slot: Slot-2
    PCIe Lane Width: x16
    VRAM (Total): 256 MB
    Vendor: ATI (0x1002)
    Device ID: 0x9588
    Revision ID: 0x0000
    ROM Revision: 113-B1480A-252
    EFI Driver Version: 01.00.252
    Displays:
    CMC 22 W:
    Resolution: 1680 x 1050 @ 60 Hz
    Depth: 32-Bit Color
    Core Image: Hardware Accelerated
    Mirror: Off
    Online: Yes
    Quartz Extreme: Supported
    Rotation: Supported
    CMC 22 W:
    Resolution: 1680 x 1050 @ 60 Hz
    Depth: 32-Bit Color
    Core Image: Hardware Accelerated
    Main Display: Yes
    Mirror: Off
    Online: Yes
    Quartz Extreme: Supported
    Rotation: Supported
    ATI Radeon HD 2600 XT:
    Chipset Model: ATI Radeon HD 2600
    Type: Display
    Bus: PCIe
    Slot: Slot-3
    PCIe Lane Width: x16
    VRAM (Total): 256 MB
    Vendor: ATI (0x1002)
    Device ID: 0x9588
    Revision ID: 0x0000
    ROM Revision: 113-B1480A-252
    EFI Driver Version: 01.00.252
    Displays:
    CMC 19AW:
    Resolution: 1440 x 900 @ 60 Hz
    Depth: 32-Bit Color
    Core Image: Hardware Accelerated
    Mirror: Off
    Online: Yes
    Quartz Extreme: Supported
    Rotation: Supported
    Display Connector:
    Status: No Display Connected

    Now THAT is interesting. I typically do not have two Safari windows open and active on the same screen; I usually have three or more Safari windows open, but each is on its own screen, using tabs within each.
    I think it's fascinating to see that the content is only affected in one window on the same page.
    Can you elaborate as to your trigger? Is it FUS? Screensaver? Other?
    The suggestion in either this thread or the other to switch the window momentarily to another screen to clear the problem until the next FUS or screensaver event is my current favorite fix. I have hotkeys assigned to move a window from one screen to another, anyway, so when I return to a user session from login to see Safari schizing out, a quick screen-swap toggle clears the issues until I allow a screensaver (but not always) or engage FUS (always) and see the issue return.
    Do you have multiple screens? Can you reliably resolve the issue by swapping and returning, rather than being forced to quit Safari?
    One thing to note about the screen swap, is that when this issue is occurring, there is a tremendous lag (a solid second or so) before the window is actually moved to the other screen, and a comparable lag when returning. IOW, there is an observable and HUGE processor spike as well as a memory-use spike (seen in Activity Monitor, top, and iStat Menus) as it deals with moving the visual display (be it plain text or graphic or video content) when this bug is active, but the same action two seconds later, or the same action in any other program, nets near-instant screen movement in response to the global hotkey action.
    So, whatever it is that is borked between Safari and Core Video is not just an interpretation/ColorSync/disply error; it seems also to be leaking memory and having runaway processor cycles, as well.
    There are times when Safari, with less than ten or twenty tabs open starts eating pretty close to 2GB of RAM, and will dominate a single processor to near 100%, *without* any windows actually containing very much in the way of images, and certainly no Flash or even QT.
    I know this sounds a bit arrogant and spoiled, but thank God I have 8 cores and 8GB of RAM; I cannot imagine how this bug might feel on a single core machine with less than 2GB of RAM.

  • Desktop app startup GUI Grey out using JDK1.5 using -Xmx1152m

    Hi,
    We have a desktop swing app which works with JVM max heap size -Xmx1152m in JDK 1.4.2 without any problems. But using JDK 1.5, the GUI shows up in GREY and not repaint itseld even if we force repaint by minimising or being another windows over it.
    However, there is no problem if we reduce the -Xmx size from 1152m to about 512m and this problem does not show up on all machines.
    Is this problem anyway related to the following bug ?
    http://forum.java.sun.com/thread.jspa?forumID=32&threadID=554377
    We would appreciate if someone can help us fix this problem.
    We compiled our source code with JDK 1.5 and run with JDK1.5 and we do not use any JDK 1.5 features. We want to use JDk 1.5 for our memory and performance improvements. Ours is a heaby memory usage app so we can not afford to reduce -Xmx to 512m from 1152m.
    Thanks

    It could be to a corrupt Video Driver or Microsoft DirectX driver on that machine and 1.5 is taking advantage of some new directx methods to speed up video rendering. May 1.5 is using more vram than 1.4. You could also try downloading and installing/or reinstalling the latest Microsoft DirectX drivers and the latetest video drivers for the Dell Optiplex GX280. After that carefully read the link I provided, it might provide you with some clue as to what is going wrong and you could experiment with other ddraw properties.

  • JTree in JScrollPane not resizing after model change.

    I have a JTree in a JScrollPane that's put in a JPanel using the JGoodies FormLayout as it's layout manager. The column definition defines the column to grow so the JScrollPane should have enough space. The tree is empty when I create it and put it in the JScrollPane.
    After adding some nodes to the tree the JScrollPane does not resize automatically, it only resizes when a forced repaint occurs (moving or resizing the window , etc).
    I've tried calling invalidate(), repaint(),revalidate() on both the JTree and the JScrollPane. I also do a reload() on the TreeModel after adding the nodes (which is probably unnecessary as I use insertNodeInto(node,parent,position) from the DefaultTreeModel to add the new nodes).
    Anybody knows what I'm missing here?
    Thanks a lot in advance !

    Update:
    The card is running now. I had another Arch system (arch2) on the same network (to compare with), and after I shut that down and rebooted the first one (arch1) the network interfaces show up, both lo and eth0.
    However, the startup routine hangs about 2-3 minutes on the network daemon (with blinking router lights and hdd activity), so it's still not perfect. Another thing is that I can't get the right gateway from the router's dhcp. Here's an overview of the setup:
    Home: 192.168.2.x
    arch1 .2.102-------|
    |
    arch2 .2.101-------| old SMC router: .2.1
    |
    fritzbox .2.2 -----|
    router/modem
    |
    |
    ~~~~~
    internet
    The gateway is supposed to be the fritzbox with ip 192.168.2.2. The old SMC router serves addresses in the range .2.101-110. I set it up this way because I need the 8 ports on the SMC (and I like watching the lights).
    Here's my /etc/rc.conf for both systems:
    arch1 (starts slow):
    eth0="dhcp"
    ROUTES=(!gateway)
    arch2 (working):
    eth0="eth0 192.168.2.101 netmask 255.255.255.0 broadcast 192.168.2.255"
    gateway="default gw 192.168.2.2"
    ROUTES=(gateway)
    arch1 gets the SMC as gateway, arch2 gets the fritzbox.
    Ideally all computers on the network should get their IPs from the SMC dhcp, which also gives them the fritzbox as gateway. But that just doesn't work for the arch1. arch2 and the windows PCs get online just fine.
    I had also tried setting arch1 the same as arch2 except for the ip=2.102. Then the network starts faster, but the gateway is still stuck at the SMC router -> no internet.
    Rather complicated, but what are networks for? Anyone see daylight in this mess?
    Last edited by bitpal (2009-08-13 21:24:02)

  • How to re-paint a listbox, and to display ohms symbol w/text

    Hi All,
          Please help me build a string which includes characters from the Roman alphabet and the ohms symbol.  I thought I'd done this before, but perhaps not.
    The plan is to populate a listbox with such strings and set cell BG color to indicate test pass/fail.  BG color of all cells can be "cleared" (changed to default) by setting the color of cell (-2,-2) (thanks again becktho!)...
    ... but to see the change requires listbox to be re-painted.  Was hoping for a nice way to force repaint (besides re-size/re-pos.)
    Any help would be appreciated!
    When they give imbeciles handicap-parking, I won't have so far to walk!

    In Labview, switch to the Symbol font, then double click to make a label or comment, and type shift-W.  This makes W.
    Also, unicode 03A9 is the code for ohms.
    - tbob
    Inventor of the WORM Global

  • Problems updating gui in JApplet

    Hi,
    I have a JApplet with a JPanel with another JPanel ? TreePanel ? containing a JScrollPane with a JTree.
    When init() is run in MyApplet, treePanel is initiated with a JTree, with test data hardcoded in TreePanel?s constructor. I want the tree to change every time a thread loops, by calling method treePanel.updateResultTree(root) from the thread, with a new root. To test this, I have hardcoded a new tree content in the thread to pass to the TreePanel. In method updateResultTree(root), I remove the existing JTree from JScrollPane and add a new JTree to it, with the new root. Then I repaint the JScrollPane.
    When I run the applet, the initial tree is displayed, but it is not updated with the new JTree for the first thread loop as expected. How is the gui in a JApplet refreshed/updated?? Will SwingWoker update the gui automatically without forcing repaint()?
    Please help, I'm so stuck! Thanks in advance!
    MyApplet
    public class MyApplet extends JApplet {
       private TreePanel _treePanel;
       private UpdateHandler _updateHandler;
       private Thread _updateThread;
       public void init() {
          super.init();
          _treePanel = new TreePanel();
          // Updating thread
          _updateHandler = new UpdateHandler();
          _updateThread = new Thread(_updateHandler);
          _updateThread.start();
          // Initialize gui
          JPanel bigPanel = new JPanel();
          bigPanel.setLayout(new BoxLayout(bigPanel, BoxLayout.X_AXIS));          
          getContentPane().add(bigPanel, BorderLayout.CENTER);   
          _treePanel = new JPanel();
          bigPanels.add(_treePanel);
       // Updates the GUI every X seconds
       private class UpdateHandler implements Runnable {
          public final static int UPDATE_INTERVAL = 10;
          public UpdateHandler() { }
          public void run() {
             try {
                _displayResults();
             } catch (InterruptedException ie) {
       private synchronized void _ displayResults () throws InterruptedException {
          while(true) {
             // Resolve a new DefaultMutableTreeNode object as root to be updated in GUI
             // (For test)
             DefaultMutableTreeNode root = new DefaultMutableTreeNode(new Result("Root"));
             DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode(new Result("Result X"));
             DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode(new Result("Result Y"));
             DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode(new Result("Result X1"));
             root.add(child_1);
             root.add(child_2);
             child_1.add(child_11);
             // Update the GUI 
             _treePanel.updateTree(root);
             wait(UPDATE_INTERVAL*1000);
    }TreePanel
    public class TreePanel extends JPanel {
       private JScrollPanel _treeSrcoll;
       private JTree _tree;
       TreePanel() {
          super();
          // Test tree, displayed in applet?s init()
          DefaultMutableTreeNode root = new DefaultMutableTreeNode (new Result("Root"));
          DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode (new Result("Result 1"));
          DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode (new Result("Result 2"));
          DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode (new Result("Result 4"));
          DefaultMutableTreeNode child_12 = new DefaultMutableTreeNode (new Result("Result 5"));   
          root.add(child_1);
          root.add(child_2);
          child_1.add(child_11);
          child_1.add(child_12);
          _tree = new JTree(root);
          _treeScroll = new JScrollPane(_tree);
          add(_treeScroll, BorderLayout.CENTER);
       public void updateTree(DefaultMutableTreeNode  theRoot) {
          if (theRoot != null) {
             if (_tree!= null) {
                _treeScroll.remove(_tree);
             _ tree = new QCTree(root);     
             _treeScroll.add(_tree);
          } else {
             JLabel label = new JLabel("No result tree structure is available");
            _treeScroll.add(label);
         _treeScroll.repaint();
    }Result
    public class Result {
       private String _name; 
       public Result(String name) {
          _name = name;
       public String toString() {
          return _name;

    I found the error:
    I need to use
    treeScroll.getViewPort().add(tree);
    and
    treeScroll.getViewPort().remove(tree);

  • Rowset.jar nightmare, where do i find the latest?

    I continue to be haunted by ClassCastException whenever i try getDate(). I've seen threads that say it was fixed, but the latest rowset.jar I found on this site version 1_0_1 still has the bug.
    I'm now being forced to download j2se 1.5 and dig through it to see if I can find the rowset.jar in there and maybe just maybe it will solve all my problems.
    Has anyone else resolved this problem?

    That's great but after installing tiger (1.5) I can't
    even compile my classes because my ide Jbuiler X
    doesn't support it. Neither will my app server. So, my
    question is why doesn't sun provide the lastest
    rowset.jar on their website that is incorporated into
    tiger? Why continue to allow people to download the
    rowset implentation 1_0_1 that has bugs?If you give Sun enough money they will be more than willing to fix it for you.
    Otherwise you live with what you get.
    >
    Should developers attempt to use CachedRowSetImpl, or
    are we just wasting our time?No idea about developers in general, but I have never used them.

  • How to tell if your component is being overlapped by another

    Hi,
    I've run into a problem implementing a menu bar into my program. Here's a little graphic. :)
              |  FILE     EDIT                                                              |
              |                                                                                            |
              |                                                                                            |
              |                                                                                            |
              |     Some custom component         CustomPanel     |
              |                                                                                            |
              |                                                                                            |
              |                                                                                            |
              ----------------------------------------------------------------------Except my component uses an active rendering loop, so it covers over the flip down menu. Is there anyway to tell when something is covering the CustomPanel? Or is there anyway to explicitly tell a component to paint all overlapping components on it?
    such as: CustomPanel.paintOverlappingComponents().
    or something like that?

    Menus in swing are light weight components i believe.
    if you want them to appear over the top of an actively rendered Component, you are going to need to either :-
    1) forcefully repaint the menus as part of the active rendering. (so, repainting them each loop)
    2) when performing the active rendering, add a clip region that excludes the area that the menus take up. (avoid overpainting them at all)
    In either case, you are going to have to query the menus each render loop, to determine if they are showing or not.
    I would go for solution 2, it should be quicker.

  • When to repaint panel?

    I'm having a problem figuring out when exactly my panel is ready to be repainted. Inside this JPanel I'm loading Images and then drawing them with paintComponent. My problem is that when the panel is first painted, these images aren't loaded yet so paintComponent can't draw them. However, after a second or so these images are loaded and if I force a repaint by resizing the window everything shows up fine.
    What's the best way to repaint the panel when the Images are loaded? I tried a thread approach but I was running into problems where for some reason the images would never load (as if the thread was taking over the whole program) and I would like to avoid threads if possible. Any suggestions would be greatly appreciated.

    Synchronous loading means that your application stops everything until the image is fully-loaded, then continues on its way. Asynchronous loading means the app moves ahead without loading the image; not a desirable thing. The old boiler plate method for synchronous loading is with a MediaTracker. The newer way is with ImageIO but this requires j2se 1.4 or later. If you will load or initiate the loading of your images in the constructor of your app/component they will be ready when the app/component is first painted.
    class AnImageComponent extends JPanel
        BufferedImage/Image image;
        public AnImageComponent()
            loadImage();
        protected void paintComponent(Graphics g)
            g.drawImage(image, x, y, this);
        private void loadImage()
            // synchronously load image...
    }The override of the 'update' method is not recommended and usually not necessary in Swing. Calling 'repaint' and/or 'validate/revalidate' for updating gui components is usually done from within event code, eg, from within the actionPerformed method of a SwingTimer, a while loop inside an animation thread, or a ui component event listener.

  • Image repaint preformance and threading

    Folks,
    I'm trying to make this sucker run faster.
    My question is, can anyone please guide me, especially with regards synchronising the Threads more efficiently... I'm thinking of using join and i]notify to make the "navigator" threads yield to the swing threads, to give it a chance to repaint before continuing... does this sound sane to you?
    Currently, without the thread.sleep it paints get the first "burst", and then nothing until the alrorithm has completed... exactly not what I wanted, because the whole point of this GUI is to watch the algorithm at work... sort of a "visual debugger"... I find that watching an algorithm play out helps me to "imagineer" ways of improving it... and in this case improvement means optimisation... it's all about getting from A-J faster than anyone else on the planet, especially those smarty-wishbone-legs C# programmers ;-)
    The code is too big to post (darn that 7500 char limit!) so I'll split it over several posts here, and I've also posted it as a single download to [MazeOfBoltonGUI2.java|http://groups.google.com/group/comp_lang_java_exchange/web/MazeOfBoltonGUI2.java] on my google group (comp lang java exchange).
    Cheers all. Keith.
    package forums.maze;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.SortedMap;
    import java.util.TreeMap;
    import java.util.Stack;
    import java.util.Queue;
    import java.util.PriorityQueue;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    * A Visual debugger,
    * for the [A* Alogorithm|http://en.wikipedia.org/wiki/A*_search_algorithm] navigator
    * of the [Maze Of Bolton|http://cplus.about.com/od/programmingchallenges/a/challenge12.htm]
    * as implemented by [Prometheuz|http://forums.sun.com/profile.jspa?userID=550123]
    * with GUI by [Kajbj|http://forums.sun.com/profile.jspa?userID=91610]
    * hacked together by [Keith Corlett|http://forums.sun.com/profile.jspa?userID=640846]
    * and posted on [Sun's Java Forum|http://forums.sun.com/thread.jspa?threadID=5319334]
    * and posted on [Google news group|http://groups.google.com.au/group/comp_lang_java_exchange/]
    public class MazeOfBoltonGUI2
      static final char[][] matrix = readMatrix("map.txt");
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                MazeNavigator navigator = new MazeNavigator(matrix);
                JFrame frame = new JFrame("MazeOfBoltonGUI2");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new MainPanel(navigator));
                frame.pack();
                frame.setVisible(true);
              } catch (Exception e) {
                e.printStackTrace();
       * Reads the file into a char matrix[rows,cols] ie: an array of char arrays.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      private static char[][] readMatrix(String filename) {
        try {
          BufferedReader input = null;
          try {
            input = new BufferedReader(new FileReader(filename));
            char[][] matrix = null;
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ( (line = input.readLine()) != null ) {
              lines.add(line);
            int rows = lines.size();
            matrix = new char[rows][];
            for (int i=0; i<rows; i++) {
              matrix[i] = lines.get(i).toCharArray();
            System.err.println("DEBUG: rows="+rows+", cols="+matrix[0].length);
            return matrix;
          } finally {
            if(input!=null)input.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new IllegalStateException("Failed to readMatrix!", e);
    class MainPanel extends JPanel
      private static final long serialVersionUID = 1L;
      // button panel
      private final JButton goButton;
      // maze panel
      private final MazeNavigator navigator;
      private final Monitor<Path> monitor;
      private BufferedImage background;
      private BufferedImage image;
      private List<Path>currentPaths;
      public MainPanel(MazeNavigator navigator) {
        this.navigator = navigator;
        this.monitor = new SwingMonitor();
        this.goButton = new JButton("Go");
        goButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              final String caption = goButton.getText();
              goButton.setVisible(false);
              monitor.execute();
        add(goButton);
        setPreferredSize(new Dimension(navigator.maze.cols*3, navigator.maze.rows*3)); //w,h
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      private static Color[][] mazeColors;
      private static Color[][] createMazeColors(Maze maze) {
        Color[][] colors = new Color[maze.rows][maze.cols];
        for (int r=0; r<maze.rows; r++) {
          for (int c=0; c<maze.cols; c++) {
            colors[r][c] = getColor(maze.matrix[r][c].ch);
        return colors;
      }*... PTO ...*

    I'm persuaded that the main issue (no intermediate results drawn) is the improper use of SwingWorker.
    When you've got over it, you may want to consider other smaller-effect optimizations:
    Reconsider usage of an offscreen image*
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      }At first I didn't get why you wanted to draw an offscreen image, then paint it to the screen, all that in the EDT.
    After reading the draw() method more closely, I guess you want to ease the coding of the scaling: you draw an image where one cell = one pixel, then paint the image, scaled to the panel's display size.
    In terms of performance, I don't know how it stands:
    On one hand, the image creation if lighter (1 pixel per cell). And you have a point that the built-in scaling offered by Graphics2D.drawImage(image, size) may be efficient. I can't comment on that, I hope the granphics and hardware acceleration folks will pop in the thread.
    On the other hand, if the built-in scaling had poor performance, it may be good to try what "manual" scaling would bring you. That means, in a simplified version, skip the offscreen image creation, and draw directly on the paintComponent()'s Graphics2D argument. the drawing of a cell at coordinates c,r, for example, would look like:
    g.fillRect(c*CELL_WIDTH, r*CELL_HEIGHT, WIDTH, HEIGHT);Performance apart, the scaling as you do it currently has functional drawbacks, if you want pathes as 1-pixel width lines over large cells:
    - if the maze is smaller (in rows, columns) than the panel displaying it (in pixels), the cells will be scaled but the pathes too: so your 1-pixel lines appear as large as the cells. May or may not be a desired effect.
    - if the maze is larger than the display panel, the cells are shrinked, fine, but the so are the path lines, to a point where they may be invisible (probably depending on color blending, I'm a n00b at graphics operations).
    But maybe I misunderstood the need, and maybe the intended drawing of a path is actually the drawing of the rectangles of all its traversed cells, in special path colors?
    Reconsider intermediate allocations*
    Each paintComponent() call results in the allocation of a 2D-array of Color objects (method createMazeColors(Maze)).
    I don't see what the mazeColors array brings you. I assume you wanted to decouple the determination of colors (depending on cell state) and the rendering of the colors: what does it bring: no performance advantage (on the contrary, it adds a 2D array allocation, and 2xN^2 2D-array access), and does not improve the code readability either (subjective rant, sorry).
    Why don't you pass the Maze as an argument to the draw() method, and call the getColor(cell.ch) from there?
    Side note, maybe a bit subjective: performance apart, the design of the usage of this mazeColor array is a no-go!
    An instance method alters a static variable reference,which is used subsequently in another instance method, with no synchronization. The current code does that in a single thread (+paintxxx()+ is only called in the EDT), which keeps that safe (I'd dare to say: by luck), but considerations exposed below may have you refactor the design to introduce other threads, and may exhibit the thread-unsafety of this design.
    Consider drawing the image in a background thread.*
    Indeed the technique of drawing to an offscreen image is quite common, but it is often done to improve responsiveness (not raw performance) of Swing applications. Here is a resource about this (what the author calls the passive approach), although it doesn't use a background thread.
    The idea is that if a paintCompobnent() methods involves lots of computation (arithmetics of traversing a 2D model, scaling things, etc.), this takes CPU times in the EDT, and all subsequent events (such as, a MouseEvent, but also other painting events) keep pending on the event queue, which is consumed by the single event-dispatch thread. The result is that the UI appear unresponsive, and painting of other areas may seem hung.
    The idea is to move the computation to a background thread, which posts rendering to the EDT when the Image is ready to be displayed.
    Of course this doesn't gain any CPU time. This only ensures the EDT uses a minimal part of this CPU (only render and image and process events), instead of performing the whole computation.
    In your case you already have a background thread, and indeed an appropriate choice, a SwingWorker. The application of this technique would consist in calling the draw() method in the worker thread (in the update(Path) method), and invoke super.publish() only after the image has been updated. Note that the process(List<Path>) could then ignore its argument (you may reconsider the choice of type parameter of the worker), and simply get the latest version of the image attribute).
    Of course in this technique, the offscreen image filling is called synchronously from the Navigator, so this halts the algorithm part itself, for the duration of the image generation. You may refine the technique by spawning a dedicated thread for the image generation - with subtle guard code to handle occasions when the algorithm goes faster than the image generation, and posts a new update(Path) while the image generation for the previous path has not completed yet...
    Recuce the number of things to redraw*
    Two parts:
    first, depending on the number of cells and pathes, there may be (yet another) optimization, to not redraw the whole offscreen image, but only the cells/path that have changed in the last update(). In particular, if a path is not a line but a list of cells, then it's quite easy, reusing the current offscreen image, to only fillRect(...) the appropriate cells.
    Second, if a path is not rendered as a thin line over larger cells, but as cells themselves rendered in special path colors, you may paint cells and path in one go: instead of drawing, first the cells, then the path, draw only the cells, electing the color using a decision method such as:
    private Color getColor(Cell) {
        if (cell.getPathState()!=NOT_IN_ANY_PATH) {
            return getColor(cell.getPathState());
        else {
            return getColor(cell.ch);
    }Of course this forces you to modify your data model, and update the new pathState as part of the algorithm (or better isolated, in the update(Path) method, before invoking the drawing machinery). Maybe that was the intention of the mazeColors array?
    I haven't studied your other posts on the logic of the MazeOfBolton algorithm, so I don't know if it's acceptable for you that a cell appear to have only one path state, as opposed to one for each of the pathes that traverse it. This last trick may then seem incorrect, but please consider it as only a graphical information, and indeed your current image drawing draws only ONE path for a given cell (the last path in currentPaths that traverses this cell ).

  • Netscape 7.2 Mail "Unexpectedly Quits" after install of J2SE 5.0 Java

    My problem is with Mail & Newsgroups in Netscape 7.2 for Macintosh OS10 - Netscape quits at end of message download.
    Since "Software Update's" recent J2SE 5.0 Java update, which I installed a day or two ago, Netscape's Mail & Newsgroups has been completely unpredictable. The most annoying problem being that Netcape would quit, over and over again. Sometimes for no apparent reason, but always reliably quitting after having downloaded the last message from the server. Poof! Window gone, program quit. And with each launch of Netscape, more messages in my Inbox. I finally was forced to change the server settings so that messages wouldn't download automatically. I could then delete them from my Inbox... if I could do so quickly enough. Sometimes the program would quit before I could make the necessary changes.
    I have read many similar complaints and suggestions involving rather complicated fixes. None worked for me.
    Here's what did work. And oh, so easy! UNCHECK "Enable Java" in Netscape's preferences. You will find the box in the Netscape/Preferences/Advanced pane. Apparently Netscape Mail & Newsgroups doesn't like the new J2SE 5.0 Java update.
    So far I've seen no adverse effects from this in the Netscape 7.2 browser. However, I would like to know that Java is at work in the background as usual in ALL my browsers. Since Apple doesn't support Netscape, I am counting on an answer from another user.
    Power Mac G4 "Quicksilver"   Mac OS X (10.4.6)   800 Mhz Dual Processor, 1.5GB RAM
    Power Mac G4 "Quicksilver"   Mac OS X (10.4.6)   800 Mhz Dual Processor, 1.5GB RAM

    Scapsuiter, Thanks for pointing me in the right direction. I still don't know why Java effected Netcape's mail the way it did, or even if that was really the culprit. But I did a little investigation into the MRJ plugin for Mac OS X (which I HAVE NOT installed). I found a sight that could be used to see if Java was really working in my browser (namely, "Walter Fendt’s Java Applets on Physics"). To test Netscape's bowser and mail I once again enabled Java. The applet worked fine in the browser. But here's what I don't understand. Now Netscape's Mail & Newsgroups feature is working exactly as it should, behaving just as it did before the problem. Is it possible that Netscape was simply overloaded with such a huge amount of messages as it downloaded them again and again, duplicating them each time I quit & re-launched the program? This seems unlikely as I've seen Netscape handle huge numbers of messages before, in various sub-folders and even the trash. My concern is since I don't know what caused the problem, it could happen again. I guess time will tell. I still have much to learn, but thanks for your response and for helping to further my knowledge on Java applets and the MRJ plugin.

Maybe you are looking for

  • Simultaneous audio from outputs 1-2 and outputs 3-4?

    Hi guys, How do I get simultaneous audio from outputs 1-2 and outputs 3-4? I'm running Logicpro 7.1 through an M-Audio FW 410 hardware interface. I'm trying to set things up so I can monitor through my mixing board to eleminate the weird echo sound y

  • Uninstallation & re-installation issues

    I had an issue with purchasing "actions" & it caused my Guided Edits & other tabs to dissapear. I read on other fourms to uninstall & reinstall Adobe PSE 10 because the "actions" I purcahsed created this issue. SO, tonight I uninstalled PSE & went to

  • Application toolbar missing in Dreamweaver CC (Was: Appiction toolbar missing)

    Can anyone help I'm new to dreamweaver and have recently installed a new cloud download installation, but I think it might be incomplete I cant find the appliction tool bar

  • "The extentions does not contain a valid signature"

    Hi, i got a problem when i installing RA Beauty retouch "The extensions does not contain a valid signature", can anyone help me cause i really want use this extention, running on macos  10.9.4 and adobe extention manager CC ! And i already uncheck Ex

  • Firefox will not open today, it hangs, google chrome is fine

    Firefox launches with telegraph.co.uk as default. No problems before. Today it hangs and even trying to delete telegraph.co.uk doesn't work , at least one second to delete one character, then if I type in igindex.co.uk and press return, it just hangs