Synchronous painting

Hello!
I need help in writing a program which uses a synchronous painting. My program looks like this:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Draw extends JPanel{
private JFrame frame = new JFrame ();
public Draw (){
frame.getContentPane ().add (this,BorderLayout.CENTER);
frame.pack ();
frame.setSize (new Dimension (300,200));
frame.setVisible (true);
public static void main (String[] args)
{Draw draw = new Draw ();}
public void paintComponent (Graphics gr){
super.paintComponent (gr);
gr.setColor (Color.blue);
Random r = new Random(System.currentTimeMillis ());
for(int i=0 ; i<2000000 ; i++){
int x1 = r.nextInt (this.getWidth ());
int y1 = r.nextInt (this.getHeight ());
int x2 = r.nextInt (this.getWidth ());
int y2 = r.nextInt (this.getHeight ());
gr.drawLine (x1,y1,x2,y2);
How can I modify the code so that I see every line drawn after I call drawLine(...) ?
Thanks!

It inpossible to tell from your query whether you want to progress towards a solid blue panel or only have one line showing at a time.
The following code shows both. It is rigged toward showing all lines without clearing. To change to one line showing follow the comment directionsimport javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Draw extends JPanel implements ActionListener
   private JFrame frame = new JFrame ();
   private int x1 = 0,x2 = 0,y1 = 0,y2 = 0;
   private Random r;
   private Graphics g;       //comment out for single line
   public Draw ()
      super(false); //not double buffered
      r = new Random(System.currentTimeMillis ());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(this);
      frame.pack ();
      frame.setSize (new Dimension (300,200));
      frame.setVisible (true);
      drawLines();
   private void drawLines()
      g = getGraphics();            //comment out for single line
      g.setColor (Color.blue);      //comment out for single line
      int delay = 30; //milliseconds - adjustable
      //forget 2 million, this will run forever if you let it
      new javax.swing.Timer(delay, this).start();
   public static void main (String[] args)
   {Draw draw = new Draw ();}
   public void actionPerformed(ActionEvent evt)
      x1 = r.nextInt (this.getWidth ());
      y1 = r.nextInt (this.getHeight ());
      x2 = r.nextInt (this.getWidth ());
      y2 = r.nextInt (this.getHeight ());
      g.drawLine (x1,y1,x2,y2);      //change to repaint(); for single line
   public void paintComponent (Graphics gr)
      super.paintComponent (gr);
      drawLines();            //comment out for single line
      gr.setColor (Color.blue);
      gr.drawLine (x1,y1,x2,y2);
}

Similar Messages

  • Question about using paintImmediately()

    Hello,
    In my experience with creating animation in swing, the asynchronicity of the call to paint() causes choppiness and delays in the animation. Therefore, this time around, rather than call repaint() I'm calling paintImmediately() as the article at http://java.sun.com/products/jfc/tsc/articles/painting/index.html#paint_process tells me that such a call occurs synchronously (you'll have to scroll down to "synchronous painting"). However, it also says
    Additionally, the rule for invoking this method is that it must be invoked from the event dispatching thread; it's not an api designed for multi-threading your paint code!which has me a little worried. I don't plan to multi-thread my paint code, and from what I understand, all swing components already run in the event dispatching thread (though my understand of this is very limited and probably distorted), but I was hoping someone more knowledgeable than I can have a look at my code and tell me if everything looks 'safe':
    import javax.swing.*;
    import java.awt.*;
    import java.awt.BorderLayout;
    public class AnimationJPanel extends JPanel {
    // JPanel width and height
    private int w = 300;
    private int h = 300;
    // circle's dimensions
    private int cx = 0;
    private int cy = 150;
    private int cw = 20;
    private int ch = 20;
    public boolean B = true;
    public AnimationJPanel() {
      setSize(w, h);
      setLayout(new BorderLayout());
      // JLabel for testing purposes
      JLabel L = new JLabel("This is an AnimationJPanel");
      L.setForeground(Color.RED);
      L.setHorizontalAlignment(SwingConstants.CENTER);
      //add(L);
      // background to be black, circle red
      setBackground(Color.BLACK);
      setForeground(Color.RED);
      setOpaque(true);
    public void animate() {
      // values to increment circle's position by
      int xinc = 1;
      int yinc = 1;
      // keep incrementing circle's position until it hits the edge of the JPanel
      // then negate its increment value
      while(B) {
       cx += xinc; cy += yinc;
       if (cx >= w-cw || cx <= 0) xinc *= -1;
       if (cy >= h-ch || cy <= 0) yinc *= -1;
       paintImmediately(0, 0, 300, 300);
       try {Thread.sleep(5);} catch(InterruptedException IE) {}
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.drawOval(cx, cy, cw, ch);
    }I made this program available as a JWS at [http://www.shahspace.com/JWS/animation.html] if you want to see it (it's basically just a circle bouncing off the borders of a JPanel within a JFrame).
    Should I see to it that the call to paintImmediately() be invoked from the event dispatching thread (if it's not already)? If so, it would seem this requires creating a Runnable. I could make my customized JPanel implement runnable and execute the animation code from within its run() method. Would this be the choice way of doing it? And to preserve synchronicity, I would use invokeAndWait() - correct?
    Edited by: gib65 on Jun 25, 2010 2:19 PM
    Edited by: gib65 on Jun 25, 2010 2:21 PM
    Edited by: gib65 on Jun 25, 2010 2:23 PM

    gib65 wrote:
    In my experience with creating animation in swing, the asynchronicity of the call to paint() causes choppiness and delays in the animation. We generally don't call paint directly but rather repaint. It could be that you're not animating correctly -- hard to tell as we don't see an SSCCE of your code that uses repaint.
    Therefore, this time around, rather than call repaint() I'm calling paintImmediately() as the article at http://java.sun.com/products/jfc/tsc/articles/painting/index.html#paint_process tells me that such a call occurs synchronously (you'll have to scroll down to "synchronous painting"). However, it also says
    Additionally, the rule for invoking this method is that it must be invoked from the event dispatching thread; it's not an api designed for multi-threading your paint code!which has me a little worried. I don't plan to multi-thread my paint code,You'd better if you're going to create your own event loop. Again, are you absolutely sure that you need this?
    and from what I understand, all swing components already run in the event dispatching thread (though my understand of this is very limited and probably distorted), but I was hoping someone more knowledgeable than I can have a look at my code and tell me if everything looks 'safe':Again, if you are dead set on doing it this way with your own event loop, you'll need to make changes so that paintImmediately is called off the EDT.
    I made this program available as a JWS at [http://www.shahspace.com/JWS/animation.html] if you want to see it (it's basically just a circle bouncing off the borders of a JPanel within a JFrame).
    Actually not since the program the program never gets or uses the borders of the JPanel. Instead it bounces off your h and w constants.
    Should I see to it that the call to paintImmediately() be invoked from the event dispatching thread (if it's not already)? If so, it would seem this requires creating a Runnable. I could make my customized JPanel implement runnable and execute the animation code from within its run() method. Would this be the choice way of doing it? And to preserve synchronicity, I would use invokeAndWait() - correct?As written your current code will freeze the EDT. Myself, I'd use a Swing Timer and forget paintImmediately.
    But if you absolutely need paintImmediately, it's relatively easy to make sure that it is called on the EDT:
      public void animate() {
        // ... code deleted
        while (B) {
          //... code deleted
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                paintImmediately(0, 0, w, h);           
            try {
              Thread.sleep(5);
            } catch (InterruptedException IE) {
      }Just make sure to call animate() off off the EDT in a background thread!
    Edited by: Encephalopathic on Jun 25, 2010 3:27 PM

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • Issue with Report Painter

    Hi All,
    I have came across a strange problem in a current issue where a custom Repost Painter have been developed for 'New GL Reporting Library', it has to show Actual/Plan/ZGRS/FI10 outputs in a single report.
    The report layout is like this,
    Report                 ZPC-0001      ZGRS & FI10 Reporting - Act/Plan//Var                             Horizontal page 1  /
    Section                0001          Act/Plan/Var - ZGRS
    Standard layout        ZPC-001
    Format group:                                      0                  0                  0                  0
    Account Number/Account Description-ZGRS                  Actual              Plan            Var.(abs.)          Var.(%)
    ******       Goodwill Cost                            XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    ******       Goodwill Amort.                          XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    *******      Goodwill NBV                             XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    *****        Patents and Trademarks Cost              XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    *****        Patents and Trademarks Amort.            XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    ******       Patents and Trademarks NBV               XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    *****        Development Costs Cost                   XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    *****        Development Costs Amort.                 XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX     XXX,XXX,XXX.XX
    Now, when we are executing the output transaction with the desired inputs we are getting correct data for fiscal year 2011 whereas for fiscal year 2010 we are not getting Sales Cost data for ZGRS output whereas for fiscal year 2012 we are not getting the Sales Cost in FI10 output, whereas as per the standard output both Sales Cost data present in ZGRS and FI10 have to be synchronous.
    The selection screen is like below:
    Fiscal Year                     2011
    Plan Version                    0
    From Period                       1
    To Period                        16
    Company Code                    0100               to
    Profit Centre Group
    Or value(s)                     1602               to
    Financial Statement Version     ZGRS.Z
    Or value(s)                                        to
    Cost Element Group
    Or value(s)                     841000             to
    Target Currency (Local Crcy)    GBP
    Exchange Rate Date              28.09.2011
    Exchange Rate Type              M
    Edited by: subhajit.roy on Sep 28, 2011 12:31 PM

    The output for fiscal year 2011 is coming as :
    Report: Plan/Act/Var - ZGRS                                                       Page:   2 /  4
    Profit Centre/Group: 1602            Description: Speciality Legacy AR.
    Reporting Period:   1 to 16          Report Executed On:   28.09.2011
    Fiscal Year: 2011                    Time Report Executed: 07:55:35
    Account Number/Account Description-ZGRS                  Actual              Plan            Var.(abs.)          Var.(%)
                841000  Sales Costs                            18,947.26                             18,947.26
    *           Other General Expenses                         18,947.26                             18,947.26
    **          Other Operating Charges                        18,947.26                             18,947.26
    ***         Total Other Operating Charges                  18,947.26                             18,947.26
    ****        Total Operating Costs                          18,947.26                             18,947.26
    *****       Operating Profit/(Loss)                     9,260,718.91-                         9,260,718.91-
    ******      Profit/(Loss) Before Interest               9,260,718.91-                         9,260,718.91-
    *******     Profit/(Loss) Before Tax                    9,260,718.91-                         9,260,718.91-
    ********    Profit/(Loss) After Tax-Cont Operation      9,260,718.91-                         9,260,718.91-
    *********   Group Profit/(Loss) for Financial Year      9,260,718.91-                         9,260,718.91-
    **********  Profit/(Loss) for Financial Year            9,260,718.91-                         9,260,718.91-
    *********** Account
    Report: Act/Plan/Var - FI10                                                       Page:   3 /  4
    Profit Centre/Group: 1602            Description: Speciality Legacy AR.
    Reporting Period:   1 to 16          Report Executed On:   28.09.2011
    Fiscal Year: 2011                    Time Report Executed: 07:55:35
    Cost/Revenue Element & Description-FI10                  Actual              Plan            Var.(abs.)          Var.(%)
      841000  Sales Costs                                      18,947.26                             18,947.26
    * Variance Total                                           18,947.26                             18,947.26
    I hope I am clear in making you all understand the issue, please let me know how i can rectify this issue and provide proper data for fiscal year 2010 and 2012.

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

  • Paint JProgressBar in new Thread

    Hi,
    I have a DnD Applet for managing your computer(files and folders) at work from home and have a problem with painting a JProgressBar during the drop action. I've tried to paint the JProgressBar in a new Thread but it freezes. I can see the progressbar but it doesn't move.
    I can't do the other things that I wan't to do in drop in a new Thread because of other circumstances so I have to paint the progressbar in a separate thread. Why doesn't the progressbar move?
    Any ideas?
    public void drop(final DropTargetDropEvent dtde) {
    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    Thread t = new Thread() {
    public void run() {
    paintThread(); // THIS IS WHERE I PAINT THE PROGRESSBAR
    t.start();
    // HERE FOLLOWS THE OTHER THINGS I WANT TO DO IN DROP...
    Isn't threads supposed to work side by side?

    What you're trying to do is making a myThread method that extends Thread. It's not possible to make a method inherit from anything.
    You can't make a class with void either, a class doesn't return anything. You have mixed a class declaration and a method declaration. It doesn't make any sense at all...sorry!
    And I don't think you have got the idea with synchronized and what that means...

  • How to wait until all components painted?

    Hi - I have searched for hours for an answer to this and have yet to find something so any help is much appreciated!
    Ive posted some code below to simulate the problem im facing. This is a simple frame which has a couple of custom jPanels embedded within it.
    When this is run, the first 3 lines i see are:         I want this comment to be the last thing output
            Now finished panel paint
            Now finished panel paintBut, as this output suggests, i want the "I want this comment to be the last thing output" line to be displayed after the two panels are completely painted on the screen (in real life i need to know my components are displayed before the program can move on to further processing). Of course, if you cause a repaint you see the "now finished panel paint" each time, but im not interested in this, im simply interested in how to overcome this when the frame is first created and shown.
    Ive tried everything i can think of at the "// ***** What do i need to put here? ******" position but nothing seems to work... In short my question is how can i construct my frame and get it to ensure that all components are fully displayed before moving on?
    Sorry if the answer to this is obvious to someone who knows these things, but its driving me mad.
    Cheers
    import javax.swing.*;
    import java.awt.*;
    public class Frame1 extends JFrame {
      public static void main(String[] args) {
        Frame1 frame1 = new Frame1();
        // ***** What do i need to put here? ******
        // to ensure that the System.err.. call below
        // is only executed once both panels paint methods
        // have finished?????
        System.err.println("I want this comment to be the last thing output");
        System.err.flush();
      public Frame1() {
        this.getContentPane().setLayout(new FlowLayout());
        MyPanel  p1 = new MyPanel(); p1.setBackground(Color.red);
        MyPanel  p2 = new MyPanel(); p2.setBackground(Color.green);
        this.getContentPane().add(p1, null);
        this.getContentPane().add(p2, null);
        this.pack();
        this.setVisible(true);
      class MyPanel extends JPanel {
        Dimension preferredSize = new Dimension(200,200);
        public Dimension getPreferredSize() { return preferredSize;  }
        public MyPanel () { }
        public synchronized void paintComponent(Graphics g) {
          super.paintComponent(g);  //paint background
          // do some irrelevant drawing to simulate a bit of work...
          for (int i=0; i<200; i+=20) {
            g.drawString("help please!",50,i);
          System.err.println("Now finished panel paint"); System.err.flush();
        } // end of MyPanel
      }

    Thanks both for your replies.
    When doing the "Runnable runnable = new Runnable(){public void run(){ frame1.paint(frame1.getGraphics());....." method i sometimes see
        Now finished panel paint
        Now finished panel paint
        I want this comment to be the last thing output       
        Now finished panel paint
        Now finished panel paintwhich is a pain.
    As for making a new Runnable to do the system.err.println and then doing the SwingUtilities(invoke) on that runnable, that didnt work for me at all.
    So... in the end, my solution was to have the paint method set a boolean when finished and the main program sleep while this is false
         // Dont want to sleep for say a few seconds as cant be sure
         //painting will be finished, must monitor state of painting ...
         //therefore use while loop
         while (!isOk) {  // isOk is true when both panel paint methods complete
             System.err.println("Waiting......");
             try{   Thread.sleep(300 /* wait some time */);  }
             catch(Exception e){}
           System.err.println("Thankfully this works");which is a kind of mixture of both your suggestions i guess!
    Thanks for your help, much appreciated.

  • Some two threaded image prepare and painting applet coordination problem

    hi all,
    i'm sure this multithreaded gui is complex but anyway. a simple producer&consumer type applet. there is one seperate thread preparing an offscreen image, and the main guy draws it on applet. i can not coordinate them, what's wrong i don't know. simply, applet starts a thread, which paints something on an offscreen image, and then tells to applet repaint(). anyway, here is the code, this small png files are a lot, idea is making a view on them, just imagine a big big png file divided into matrices. afterall this is not the important part. what i see on the screen is, if you ask, nothing.
    thanx,
    ozz
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.lang.reflect.Array;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MapViewer
         extends JFrame
         Image map[][];
         public MapViewer()
              int dimensions[] = { 58, 46 };
              map = (Image[][]) Array.newInstance(Image.class, dimensions);
              try
                   loadImages();
              catch(Exception e)
                   e.printStackTrace();
         public void loadImages()
              throws Exception
              for(int i=0; i<58; i++)
                   for(int j=0; j<46; j++)
                        StringBuffer sb = new StringBuffer();
                        sb.append("C:\\map\\");
                        sb.append(i+1);
                        sb.append("_");
                        sb.append(46-j);
                        sb.append(".png");
                        map[i][j] = Toolkit.getDefaultToolkit().getImage( sb.toString() );
         public void go()
              initComponents();
              show();
         private void initComponents()
              addWindowListener
                   new java.awt.event.WindowAdapter()
                        public void windowClosing(java.awt.event.WindowEvent evt)
                             exitForm(evt);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new MapPanel(), BorderLayout.NORTH);
              pack();
         private void exitForm(java.awt.event.WindowEvent evt)
              System.exit(0);
         public static void main(String args[])
              new MapViewer().go();
         private class MapPanel
              extends JPanel
              implements MouseMotionListener, Runnable
              private int north = 1;
              private int east = 2;
              private int south = 4;
              private int west = 8;
              private int direction;
              private Image model;
              private Boolean refreshModel = Boolean.TRUE;
              private Boolean modelReady = Boolean.FALSE;
              private Point start = new Point(200, 200);
              public MapPanel()
                   addMouseMotionListener(this);
                   new Thread(this).start();
              public synchronized Image requestImage()
                   return createImage(1600, 1600);
              public Dimension getMinimumSize()
                   return new Dimension(400, 400);
              public Dimension getPreferredSize()
                   return new Dimension(400, 400);
              public void paint(Graphics g)
                   synchronized(modelReady)
                        if(modelReady.booleanValue() == true)
                             g.drawImage(model, 0, 0, null);
                   g.setColor(Color.white);
                   g.fillRect(0, 0, 30, 10);
                   g.setColor(Color.black);
                   g.drawString(String.valueOf(direction), 0, 10);
              public void mouseDragged(MouseEvent e)
              public void mouseMoved(MouseEvent e)
                   Point p = e.getPoint();
                   findDirection(p);
              private void findDirection(Point p)
                   direction = 0;
                   if(p.x < 100)
                        direction |= west;
                   else if(p.x > 300)
                        direction |= east;
                   if(p.y < 100)
                        direction |= north;
                   else if(p.y > 300)
                        direction |= south;
              public void moveIt()
                   int px = 20;
                   int py = 20;
                   synchronized(refreshModel)
                        if(refreshModel.booleanValue() == true)
                             model = requestImage();
                             if(model == null || model.getGraphics() == null)
                                  return;
                             Graphics g = model.getGraphics();
                             for(int x=0; x < 4; x++)
                                  for(int y=0; y<4; y++)
                                       g.drawImage(map[px+x][py+y], x*200, y*200, null);
                             refreshModel = Boolean.FALSE;
                             modelReady = Boolean.TRUE;
    //               start.x -= 3;
    //               start.y -= 3;
              public void run()
                   while(true)
                        try
                             moveIt();
                             repaint();
                             Thread.currentThread().sleep(20);
                        catch(InterruptedException ie)

    Hi.
    The Graphics.drawImage method is asynchronyous, that may be the reason of the problem. Set an ImageObserver parameter in drawImage method, when drawing on an offscreen image. Count finished images and when all are done
    draw the big image on the screen.
    Alternatively you can call Toolkit.prepareImage method in a loop, after loadimages and wait until all images are loaded(true returned).

  • Canvas paint never gets called - Repaint and ServiceRepaints.

    I have a problem that My Canvas never gets Drawn or the Image never gets Displayed;
    I am not sure if there is a DeadLock or If there is nothing to be painted,
    but when I enable the Debugger I notice that it never enters the paint method. ( I call Repaint and ServiceRepaints)
    If however I make the thread that calls setImage external to my Canvas Class the images do get Displayed.
       //Create the Canvas Class, Start Thread Display Canvas
       frame = new ImageCanvas();
        frame.addCommand(exitCommand);
        frame.addCommand(backCommand);
        frame.setCommandListener(this);
        frame.start();
        display.setCurrent(frame);
    //Display Image
    public class ImageCanvas extends Canvas implements Runnable {
    protected void paint(Graphics g) {
      g.drawImage(offscreen, Constants.XPOS, Constants.YPOS,  Graphics.LEFT | Graphics.TOP);
      private void setImage(Image img, String title) {
        this.setTitle(title);
        offscreen = img;
        repaint();
        serviceRepaints();
    public void run() {
         while(true){
           if (Constants.IMGLOCK != null) {
             synchronized (Constants.IMGLOCK) {
                setImage(Constants.IMAGE, title);
                Constants.IMGLOCK.setLockBoolValue(false);
                 image_created = true;
          } else {
               Constants.IMGLOCK.wait(10);
    }

    I found the BUG, But do not understand Why this is Needed to add,
    the Canvas every Time to the Display.
    Can someone please Explain ???
    private void setImage(Image img, String title) {
        this.setTitle(title);
        offscreen = img;
        repaint();
        display.setCurrent(this);  //<<<<<<WHY ????
        serviceRepaints();
      }

  • Help request - JFrame re-use problem - Painting issues

    Hello,
    I'll give a short background on the problem:
    The general purpose of my program is to display a series/sequence of screens in a spesific order. I have constructed an object (JFrame) for each of those screens. In the beginning I create a Vector containing information about every screen in the sequence and when the time comes for that screen to appear I use that information to create the screen.
    In my first design I created a new object for each screen (I have 6 basic types of screens but they often appear with different data - graphs and tables and such) while after I was done with a screen I released the reference to it. For some reason the memory requirement of that design were immense and kept increasing with each new screen.
    To remedy that I switched to a re-usage (recycling sort of say) design. I created a cache of screens, 1-2 of each type depending on whether two screens of the same type may appear one after the other. When a screen appears for the first time, I use the constructor to initialize it and save it in the cache but for future usage I "re-initialize" the old screen with the new data. Only after I finished re-initializng the screen I set it's visibility to true.
    Coming to the problem at last: as I understand seeing as the update of the frame's contents finishes before the screen is displayed it should already be displayed in it's updated form, BUT instead it appears with the old data for a split second and then repaints on-the-fly. You can actually see some components disappearing/appearing. This is a pretty nasty visual effect that I cant figure out how to overcome but worst of all I dont understand WHY it happens...
    **Edit:* Please read P.S. 3, just to show, this is not because I have a slow computer (it's quite new and has plenty of RAM) and I gave the heap plenty of space so it's not an issue of increasing it with each allocation
    I kindly ask for any help/advice on why the problem happens and how to fix it.
    Thank you in advance.
    P.S. I tried to pipeline the updates, say screen 1 is currently displayed so when the button to move on to screen 2 is pressed, screen 3 is re/initialized and so on. I used a seperate thread but it was synchronized with the displaying method so it should've been just like sequential updates but only less time consuming. When that didn't work I did the sequential update (which I described above) which didn't work either.
    P.S. 2. I gave the background in case it might help and to show that an advice of the sort "don't re-use and just create a new object" is out of the question =\
    P.S. 3 Something very odd I nearly forgot to mention: I work in Eclipse, and when I run it there I don't encounter this problem, it runs smoothly and there are no such painting problems but when I run it externally from the command line, that's where these problems occur and that is how the program will eventually be used. I don't understand why there is a difference at all, after all the JVM is one and the same in both cases, no? =\
    Edited by: Puchino on Dec 24, 2007 10:06 PM
    Edited by: Puchino on Dec 24, 2007 10:12 PM

    First off, It SEEMS I solved the problem by calling dispose() on the frame once I finished using it, then comes the manual updating and when I set it's visibility to true it no longer does any of weird painting problems it used to. Question is why does it work? I assumeit has something to do with the fact dispose releases the visual resources but could someone please provide a slightly more in-depth explanation?
    Second, at the moment my code doesn't have any calls to validate or invalidate or repaint (and I can't call revalidate) because JFrame doesn't inherit from JComponent. So I'd like to know please, which of these methods should I call in case I manually update the frame's contents?
    Third, I'll attempt to recreate a short sample code later on today (must be off now).
    P.S. Thanks for the replies!

  • Menu Causes Error In Paint

    The application is simple. Draw a circle where the mouse is located.
    Problem 1] If you click on the Menu (<File>) and then drag the mouse back into the window and move around the image becomes distorted.
    To reproduce the error(s). Simple copy the source code. Compile Target.java. Run Target.
    Target.java
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import javax.swing.*;
    public class Target extends JFrame implements ActionListener
         private JMenuItem objItemExit;
         public Target()
              super("Target");
              objItemExit= new JMenuItem("Exit");
              objItemExit.addActionListener(this);
              JMenu objMenuFile = new JMenu("File");
              objMenuFile.add(objItemExit);
              JMenuBar objMenuBar = new JMenuBar();
              objMenuBar.add(objMenuFile);
              setJMenuBar(objMenuBar);
              getContentPane().add(new Grid());
              pack();
              setVisible(true);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent argEvent) {
                        Destructor();
         public void actionPerformed(ActionEvent argEvent)
              if (argEvent.getSource() == objItemExit) {
                   Destructor();
         public void Destructor()
              dispose();
              System.exit(0);
         public static void main(String [] argCommand)
              Target objTarget = new Target();
    }Grid.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Grid extends JPanel implements MouseListener, MouseMotionListener
         private int iX;
         private int iY;
         public Grid()
              setPreferredSize(new Dimension(500, 500));
              iX = 0;
              iY = 0;
              addMouseListener(this);
              addMouseMotionListener(this);
         public synchronized int getX()
              return iX;
         public synchronized void setX(int argX)
              iX = argX;
         public synchronized int getY()
              return iY;
         public synchronized void setY(int argY)
              iY = argY;
         public void paint(Graphics argGraphic)
              Graphics2D objGraphic = (Graphics2D)argGraphic;
              int iWidth = getWidth();
              int iHeight = getHeight();
              int iTempX = getX();
              int iTempY = getY();
              // ==========
              // CREATE BUFFER
              BufferedImage objBuffer = (BufferedImage)createImage(iWidth, iHeight);
              Graphics2D objBufferGraphic = objBuffer.createGraphics();
              // ==========
              // FILL BACKGROUND
              objBufferGraphic.setColor(Color.white);
              objBufferGraphic.fillRect(0, 0, iWidth, iHeight);
              // ==========
              // DRAW IMAGE
              objBufferGraphic.setColor(Color.black);
              objBufferGraphic.drawOval(iTempX, iTempY, 10, 10);
              // ==========
              // LOAD BUFFER
              objGraphic.drawImage(objBuffer, 0, 0, this);
         public void mouseClicked(MouseEvent argEvent)
              argEvent.consume();
         public void mouseEntered(MouseEvent argEvent)
              setX(argEvent.getX());
              setY(argEvent.getY());
              repaint();
              argEvent.consume();
         public void mouseExited(MouseEvent argEvent)
              setX(argEvent.getX());
              setY(argEvent.getY());
              repaint();
              argEvent.consume();
         public void mousePressed(MouseEvent argEvent)
              argEvent.consume();
         public void mouseReleased(MouseEvent argEvent)
              argEvent.consume();
         public void mouseDragged(MouseEvent argEvent)
              setX(argEvent.getX());
              setY(argEvent.getY());
              repaint();
              argEvent.consume();
         public void mouseMoved(MouseEvent argEvent)
              setX(argEvent.getX());
              setY(argEvent.getY());
              repaint();
              argEvent.consume();
    }If anyone knows why when you click on the menu and then move around in the window and get distortion it would also be greatly appreciated because I have to add other panels to this window and the distortion over runs them.
    Thanks
    DeltaCoder

    Nope, still not working adding super.paintComponent(argGraphic); to the Grid.java paintComponent(Graphics argGraphic) method.
    Any other ideas?
    (I believe this should be placed in the bug session and hopefully be fixed. I can't see where the code is wrong.)
    DeltaCoder

  • Render component for painting without adding it to window resource?

    I am creating a printing utilitiy for my applications that involves using a component renderer similar to many of the java classes. Ideally, I would like to do the following:
    class PainterComponent extends JPanel implements PagedDocumentPainter {
      void paintDocument(PagedDocument doc){    
         Graphics2D g2 = doc.getCurrentPage().getGraphics();
         this.paint(g2);
         //do any additional rendering
    }For some reason the component above is not renderable (does not have a size) until it is first added to a JFrame or other window resource.
    Is there a way to prepare this component for rendering without using a GUI resource? setSize does not work.
    Thank you!
    Edited by: jayse.brock on Mar 10, 2008 11:06 PM

    I've only ever worked with building Swing applications which take care of the painting for me- all I have to do is tell them (the Components) where to be placed.
    I've just recently started working with the Graphics class, and for my first experiment I'm making a GraphicsTester class that is basically a JFrame. I do not add anything to the JFrame.
    However, I have a class MyShape,
        class MyShape extends Component {
            // Fields
            public final static int SQUARE = 0;
            private int type;
            // Constructors
            private MyShape(int type, int w, int h) {
                super();
                this.type = type;
                Dimension size = new Dimension(w, h);
                setPreferredSize(size);
                setMinimumSize(size);
                setSize(size);
            // Methods
            public synchronized Point getLocation() {
                return super.getLocation();
            public void paint(Graphics g) {
                switch (type) {
                    case SQUARE:
                        g.setColor(Color.BLACK);
                        g.drawRect(getLocation().x, getLocation().y, getSize().width, getSize().height);
                        g.fillRect(getLocation().x, getLocation().y, getSize().width, getSize().height);
                    default:
                        return;
        }Obviously I'm going to add more constant values that represent other shapes (TRIANGLE, CIRCLE, whatever) so I can test each one. The reason getLocation is synchronized is because I am implementing a way to 'move' the shape, and it involves multiple threads.
    Anywho, I draw this component using a render loop,
    while (!done) {
                    Graphics g = getGraphics();
                    shape.paint(g);
                    g.dispose();
    }I do not have to add my instance of MyShape (called shape ) to the JFrame to get it to be painted.
    It paints right where I set its location, and with the size I created it with (in the constructor).
    Don't know if that helps you, since I'm still designing this program, and I'm still a Graphics newbie too, but thought I'd share the experience.

  • Socket Painter w/chat

    Evenin all. I have this multithread socket program I'm writing and am having difficulty sending chat messages over the sockets. Lets say i have the server up, which is acting like a hub, and 3 clients that I want to send messages to the hub and the hub send it to all other clients. The hub only sends it to some of the clients and the message is sent to the hub every 2 inputs.
    key listener in the client:
    public void keyPressed(KeyEvent e) {
                   int key = e.getKeyCode();
                   if (key == KeyEvent.VK_ENTER) {
                        String message = name + ": " + jtf.getText() + "\n";
                        chat.add(message);
                        jtf.setText(null);
                        jta.setText(jta.getText() + message);
                        try {
                             oos.writeObject(message);
                             oos.flush();
                        } catch (IOException e1) {
                             // TODO Auto-generated catch block
                             e1.printStackTrace();
              }start of server:
    try {
                                  ss = new ServerSocket(7000);
                                  while (true) {
                                       // someone connected!
                                       client = ss.accept();
                                       InputStream is = client.getInputStream();
                                       ois = new ObjectInputStream(is);
                                       OutputStream os = client.getOutputStream();
                                       oos = new ObjectOutputStream(os);
                                       socks.add(client);
                                       // new thread for each painter that connects
                                       HubRead ht = new HubRead(ois, this);
                                       Thread t = new Thread(ht);
                                       t.start();
                             } catch (IOException e) {
                             HubRead ht2 = new HubRead(ois, this);
                             Thread t2 = new Thread(ht2);
                             t2.start();
                   }thread for hub:
    public class HubRead implements Runnable {
         private ObjectInputStream ois;
         private Hub h;
         private ObjectOutputStream oos;
         public HubRead(ObjectInputStream ois) {
              this.ois = ois;
         public HubRead(ObjectInputStream ois, Hub h) {
              this.ois = ois;
              this.h = h;
         public synchronized void run() {
              String in;
              try {
                   while (ois.readObject() != null) {
                        in = ois.readObject().toString();
                        for (Socket client : h.socks) {
                             h.oos.writeObject(in);
                             h.jta.append(in);
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (ClassNotFoundException e) {
         }client thread:
    public class PaintThread implements Runnable {
         private ObjectInputStream ois;
         private PaintClient pc;
         public PaintThread(ObjectInputStream ois, PaintClient pc) {
              this.ois = ois;
              this.pc = pc;
         public void run() {
              String in;
              try {
                   while ((in = ois.readObject().toString()) != null) {
                        pc.jta.append(in);
                   // PaintingPrimitive p = (PaintingPrimitive) ois.readObject();
                   // pp.addPrimitive(p);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }i'm pretty sure thats all the code that has to deal with sockets and messages. if anyone spots anything that is wrong, i'd gladly appreciate the feedback. What i'm trying to with a working program is when a client writes something in the GUI, that message is sent to the hub, and the hub sends the message to all connected.
    thanks!

    There are lots of high-level problems here.
    1. The first method executes network operations in the AWT thread. This is liable to block and freeze your GUI.
    2. The second method executes I/O code in the accept() thread. This is liable to block and delay subsequent clients from connecting. All the I/O should take place in the client thread started when the socket is accepted. That includes constructing ObjectInputStreams and ObjectOutputStreams. Also here the variables 'ois' and 'oos' should be scoped to the Runnable of that thread. They appear to be members of the class that does the accepting. So you are overwriting them for each new client.
    3. Always construct and flush the ObjectOutputStream before the ObjectInputStream for the same socket. Otherwise you can get deadlocks.
    4. You have a class called PaintThread that does I/O. It can't possibly do painting as well. Something wrong somewhere.

  • Quesion about BasicToggleButtonUI's paint() method

    hi,everybody,
    I read the source code of BasicToggleButtonUI today and confused about it.
    As what you see,a JToggleButton has two states.When you pressed the button,
    the background color will changed.It remain the background unless you press the
    button again.
    However, I found that the paint() method and painticon() method are quite similar to
    these of BasicButtonUI which is the super class of BasicToggleButtonUI.I could not found
    the snippet to keep the background color. Can anybody who is mastered in this to tell me
    why?
    thx in advancd.

    My question is, is there any way to ensure that a repaint() is completed before the program will move on?If you are not running multiple threads, then the answer is Yes...it already does. Chances are you are using the AWTEventQueue thread to do all of your work. When you click on a button, it creates an Event and puts it on the EventQueue. When repaint is called, an event is created and placed on the queue. Each event in the queue is processed by one thread, ONE AT A TIME, in the order that they were put into the queue.
    If you have multi-threaded your application, you will have to learn more about how to handle multi-threading in GUI's. Typically synchronized(getTreeLock()) will help...sometimes.
    If you don't know if you have multi-threaded or not....then you haven't done it.
    Usually this type of issue is a coding error. If you post some code maybe someone else can spot the problem.

  • Logical Formulae in Report Painter

    Hi,
    How do we insert a logical formula in a report painter.
    For instance, "IF-THEN-ELSE".
    Your early replies would be appreciated..

    You would create a formula column in reports or formula variables to use in columns. 
    More details on link's below:
    http://help.sap.com/saphelp_erp2005/helpdata/en/5b/d22c6243c611d182b30000e829fbfe/frameset.htm
    http://help.sap.com/saphelp_erp2005/helpdata/en/5b/d22ea043c611d182b30000e829fbfe/frameset.htm
    Best Regards,
    Daniel Scoz.

Maybe you are looking for

  • Can i upgrade my cpu or gpu in my Pavilion 15 laptop?

    So my Processer is a AMD a10 5750m apu with Radeon HD Grapics. 2.50 ghz 64 bit operating system I want to upgrade to a i7 intel processer if i can... please help!

  • In Pages; Title

              when I open a file and view the first page how do I make the title at the top of the page show the folder name as well as file name?

  • Commonly Run Back ground Jobs in MM

    Hi Gurus,      Can u tell me, what are the  commonly used reports, interfaces and weekly and monthly run jobs in sap from  MM point of view, name any few of these jobs, and jobs that are mandatory at various stages of MM cycle. Thanks & Regards, Poor

  • Mounted Drives Cause Applications to Hang on Connection Change

    When I change from wired to wireless connection to my network (or vice versa) mounted volumes seem to cause applications using those volumes to hang. This happens when going from wired to wireless, or vice versa, and happens regardless of the path (w

  • Last boy in the classroom

    Sony is the last company that didn't even enounce a JB for there devices. How pathetic. You guy's from sony deliver good hardware. But software support is really bad. (putting that in nice words ). And good software is just as important as good hardw