Dragging a drawing when double-buffering

Hopefully someone out there can help me with this...
To state the situation simply, I have an applet in which I need to select, drag, and drop in order to move them around. The applet works fine right now, but I can't figure out how to add dragging. The way I have it, you click the object, drag the mouse to where you want to move it, and let go. It then dissapears from where it was, and appears where it was placed. The prolem is that I want to actively see the object being dragged....even an outline would work. As it is, it's difficult to know what you were selecting to move.
I added a mouseDragged() function to the program, but I see no evidence of it working, which I think has something to do with the double-buffering I used. As far as I can tell, it does draw the object being dragged, it just doesn't ever show up on the screen....
I would appreciate any input anyone can offer!

With double buffering
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
public class Omove extends Frame
     BufferedImage img;
     Graphics      mg;
     Vector  v  = new Vector();
     Mobject m;
     int    iv = -1;
     int    dx = -1;
     int    dy = -1;
public Omove()
     addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);}});
     setBounds(10,10,400,300);
     v.add(new Mobject(1,30,30));
     v.add(new Mobject(1,89,120));
     v.add(new Mobject(2,130,230));
     v.add(new Mobject(3,210,60));
     addMouseListener(new MouseAdapter()     
     {     public void mouseReleased(MouseEvent m)
               if (iv != -1) putTheObject(m.getX(),m.getY());               
     addMouseMotionListener(new MouseMotionAdapter()          
          {     public void mouseDragged(MouseEvent m)
                    if (dx == -1) findTheObject(m.getX(),m.getY());     
                    if (iv != -1)
                         dx = m.getX();     
                         dy = m.getY();
                         repaint();
     setVisible(true);
private void findTheObject(int x, int y)
     for (int i=0; i < v.size(); i++)
          m = (Mobject)v.get(i);
          if (x >= m.x && y >= m.y && x <= m.x+30 && y <= m.y+30)
               iv = i;
private void putTheObject(int x,int y)
     iv = -1;
     dx = -1;
public void paint(Graphics g)
     if (img == null)
          img = (BufferedImage)this.createImage(getWidth(),getHeight());
          mg  = img.getGraphics();
     mg.setColor(Color.white);
     mg.fillRect(0,0,getWidth(),getHeight());
     for (int i=0; i < v.size(); i++)
          m = (Mobject)v.get(i);
          if (iv == i)           
               m.x = dx;
               m.y = dy;
          m.draw(mg);
     g.drawImage(img,0,0,null);
public void update(Graphics g)
     paint(g);
public class Mobject
     int x,y,t;
public Mobject(int t, int x, int y)
     this.t = t;     
     this.x = x;     
     this.y = y;     
public void draw(Graphics g)
     if (t == 1)
          g.setColor(Color.red);
          g.fillRect(x,y,30,30);
     if (t == 2)
          g.setColor(Color.orange);
          g.fillOval(x,y,30,30);
     if (t == 3)
          g.setColor(Color.blue);
          g.fillOval(x,y,50,30);
public static void main (String[] args)
     new Omove();
Noah

Similar Messages

  • Drawing with double buffering to a JFrame

    I want to create a simple JFrame and draw stuff to it via Graphic object using double buffering.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering. ( 'cause i read somewhere that swing components automaticly use double buffering ). And is this the righ approuch ( or whatever it's spelled ) ?

    I want to create a simple JFrame and draw stuff to it
    Don't do that.
    If you want to do custom rendering then use JPanel or JComponent, not JFrame.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering.
    No.
    You're also painting outside the standard paint cycle, which is a Bad Idea.
    So, essentially, everything your suggesting is the wrong way to go about things.
    In its most simple form, double buffering works something like this, though there are a whole load of subtleties to consider (such as component resizing for a start)
    public class Foo extends JComponent
        private BufferedImage image = null;
        protected void paintComponent(Graphics g)
            if (image != null)
                image = createImage(getWidth(), getHeight());
                paintBuffer(ig);
            g.drawImage(image, 0, 0, this);
        private void paintBuffer()
            Graphics ig = image.getGraphics();
            // do the rendering
            ig.dispose();
    }

  • DAQEvent=2 not fired when double buffered operations stop

    Hi,
    I am using Config_DAQ_Event_Message with DAQEvent==2 to get an event when synchronous DAQ and WFM are finished. This works fine with single buffered operation, but i get no event in double buffered mode ?
    Especially I like to get an event in case of Buffer-Underrun etc. errors.
    My hardware: PCI6111
    Software: NIDAQ6.9.3 with VisualC++
    Thanks in advance
    Michael

    Hi Michael,
    One of the possible causes of this error-10608 is a high update rate. The update rate might be high enough that you are not allowing enough time to fill the buffer with new data. This error can also be the result of having the regeneration option, within software, set to OFF. If you turn the regeneration option to ON, the error will go away. You can also reduce the update rate to see at which point you stop getting the error -10608
    I found the following links about errorcode -10843:
    http://digital.ni.com/public.nsf/websearch/EC38736BBF430DDC8625677C006F395C?OpenDocument
    http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RNAME=ViewQuestion&HOID=506500000008000000CA780000&ECategory=Measurement+Hardware.Digital+I%2FO
    regards
    TN

  • How to draw a point without double buffering?

    Hello all,
    I am drawing points as small red circles, but they are a bit ugly without double buffering. Am I able to draw the points to be nice? I mean not to draw them as just circles, but some special circle with light border that will looks much more nicer?
    Or what radius and position of the circle must be to be a nice small circle containing only 5 pixels? (upper, lower, right, left, middle)
    ps - they are ugly in the way of having a strange dot on the left side

    I use this method:
        private static final float POINT_RADIUS = 2f;
        private static final float POINT_DIAMETER = POINT_RADIUS * 2;
    private void drawPoint(float x, float y, Color c) {
            Ellipse2D point = new Ellipse2D.Float(x - POINT_RADIUS, -y
                    - POINT_RADIUS, POINT_DIAMETER, POINT_DIAMETER);
            graphics.setStroke(new BasicStroke(0.2f));
            graphics.fill(point);
    // and points looks like this:
       ***

  • JNI native drawing - Double Buffering issue

    Hi,
    I use JNI to paint from a C++ DLL onto a canvas, which works fine.
    The problem is that double buffering is not working though.
    In C++ I create an offscreen HDC, draw something on it and finally i bitblit the offscreen HDC to the parent window HDC.
    That is how double buffering is supposed to work. But each time i repaint my Canvas in Java, i see flickering:
    the background color is displayed first, then the C++ paintings are drawn.
    Since i already do double buffering in my C++ drawings, i don't know why there still is flickering.
    Should i do double buffering on my canvas also?
    How would this work, since my paint method looks like;
         private native void drawChart(Graphics g);
         public void paint(Graphics g)
              drawChart(g);
         }

    this is my lucky day :)
    the following thread on http://forum.java.sun.com/thread.jspa?threadID=562392&messageID=2767046 suggested to override the update method on the canvas, which works.
         // overridden to eliminate flicker
        public void update(Graphics g)
            paint(g);
        }

  • Double buffering on large pane

    I have a large JPanel which I'm drawing onto which is about 5000 x 5000. To eliminate screen flicker when dragging objects I'm trying to use double buffering. The problem is the image is too big and I get an out of memory error message.
    I've tried using clipped rectangles to display just the size of image needed but they give erratic results or the scrolling doesn't work. I need it to display the rest of the image when scrolling. Does anyone have any suggestions on how to solve this?
    I've thought about creating the image to be just the size of the screen and to just have the objects that are meant to be at that part but I think this would involve going from device space from user space but I don't know how to do this. Thanks.
    Alan

    ok, if you want it to be interactive with scrolling, then you have to keep the image large, but unless your video card has 71.5MB free space for that image, you're not going to get good results, not to mention CPU will be hurting if you need to do any processing of the image (transforms, loads, saves, etc.)
    options:
    1. forget interaction and just get the viewable image area and paint that portion of the image
    2. Get a graphics supercomputer!
    3. try to fake the interaction somehow
    what else? dunno, did that help

  • Problem with Double Buffering and Swing

    Hi
    I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
    The code below is in my main class under the constructor.
    Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
    public void update(Graphics g)
              // initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              // clear screen in background
              dbg.setColor(getBackground());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              // draw elements in background
              dbg.setColor(getForeground());
              paint(dbg);
              // draw image on the screen
              g.drawImage(dbImage, 0, 0, this);
         }My paint is right under neath and heres how it looks
    This snipet of code works but when I change the method to
    public paintComponent(Graphics g){
    super.paintComponent(g)...
    everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
    public void paint(Graphics g)
              super.paint(g);
              //if game starting display menue
              if (show_menue)
                   //to restart lives if player dies
                   lives = 3;
                   menue.draw_menue(g);
                   menue_ufo1.draw_shape(g);
                   menue_ufo2.shape_color = Color.DARK_GRAY;
                   menue_ufo2.draw_shape(g);
                   menue_ufo3.shape_color = Color.BLUE;
                   menue_ufo3.draw_shape(g);
                   menue_ufo4.shape_color = new Color(82, 157, 22);
                   menue_ufo4.draw_shape(g);
                   menue_ufo5.draw_shape(g);
                   menue_ufo6.shape_color = new Color(130, 3, 3); ;
                   menue_ufo6.draw_shape(g);
                   menue_turret.draw_ship(g);
                   menue_ammo.draw_ammo(g);
              else
                   //otherwise redraw game objects
                   gunner.draw_ship(g);
                   y_ammo.draw_ammo(g);
                   grass.draw_bar(g);
                   o_ufo.draw_shape(g);
                   b_ufo.draw_shape(g);
                   m_ufo.draw_shape(g);
                   s_ufo.draw_shape(g);
                   z_ufo.draw_shape(g);
                   xx_ufo.draw_shape(g);
                   info.draw_bar(g);
                   live_painter.draw_lives(g, lives);
                   score_painter.draw_score(g, score);
                   level_display.draw_level(g, level);
                   explosion.draw_boom(g);
         }I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
    Thanks in advance
    Sebastian

    This is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
    SimpleAnimationPanel.java
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(
                        "http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
    }AnimationApplet.java
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class AnimationApplet extends JApplet
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        // construct the panel
                        JPanel simpleAnimation = new SimpleAnimationPanel();
                        // put it in the contentPane of the JApplet
                        getContentPane().add(simpleAnimation);
                        setSize(simpleAnimation.getPreferredSize());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
    AnimationFrame.java
    import javax.swing.JFrame;
    public class AnimationFrame
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Mar 15, 2008 11:01 PM

  • Double buffering still gives flickering graphics.

    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    My questions are:
    Is the strategy used for double buffering correct?
    Why does it flicker?
    Why does the program change the priority a couple of times?
    Can you make fast games in JApplets or is there a better way to make games? (I think C++ is too hard)
    Here is the code:
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
    private Image dbImage;
    private Graphics dbg;
    private int radius = 20;
    private int xPos = 10;
    private int yPos = 100;
    * Initialization method that will be called after the applet is loaded
    * into the browser.
    @Override
    public void init() {
    //System.out.println(this.isDoubleBuffered()); //returns false
    // Isn't there a builtin way to force double buffering?
    // TODO start asynchronous download of heavy resources
    @Override
    public void start() {
    Thread th = new Thread(this);
    th.start();
    public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    while (true) {
    xPos++;
    repaint();
    try {
    Thread.sleep(20);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    @Override
    public void paint(Graphics g) {
    super.paint(g);
    //g.clear();//, yPos, WIDTH, WIDTH)
    g.setColor(Color.red);
    g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
    @Override
    public void update(Graphics g) {
    super.update(g);
    // initialize buffer
    if (dbImage == null) {
    dbImage = createImage(this.getSize().width, this.getSize().height);
    dbg = dbImage.getGraphics();
    // clear screen in background
    dbg.setColor(getBackground());
    dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
    // draw elements in background
    dbg.setColor(getForeground());
    paint(dbg);
    // draw image on the screen
    g.drawImage(dbImage, 0, 0, this);
    // TODO overwrite start(), stop() and destroy() methods
    }

    Somelauw wrote:
    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans.. AppletViewer is part of the JDK, not NetBeans.
    ..to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    Did you specifically mean the code mentioned on this page?
    [http://www.javacooperation.gmxhome.de/BildschirmflackernEng.html]
    Don't expect people to go hunting around the site, looking for the code you happen to be referring to.
    As an aside, please use the code tags when posting code, code snippets, XML/HTML or input/output. The code tags help retain the formatting and indentation of the sample. To use the code tags, select the sample and click the CODE button.
    Here is the code you posted, as it appears in code tags.
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
        private Image dbImage;
        private Graphics dbg;
        private int radius = 20;
        private int xPos = 10;
        private int yPos = 100;
         * Initialization method that will be called after the applet is loaded
         * into the browser.
        @Override
        public void init() {
            //System.out.println(this.isDoubleBuffered()); //returns false
            // Isn't there a builtin way to force double buffering?
            // TODO start asynchronous download of heavy resources
        @Override
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                xPos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            //g.clear();//, yPos, WIDTH, WIDTH)
            g.setColor(Color.red);
            g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
        @Override
        public void update(Graphics g) {
            super.update(g);
            // initialize buffer
            if (dbImage == null) {
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            // clear screen in background
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            // draw elements in background
            dbg.setColor(getForeground());
            paint(dbg);
            // draw image on the screen
            g.drawImage(dbImage, 0, 0, this);
        // TODO overwrite start(), stop() and destroy() methods
    }Edit 1:
    - For animation code, it would be typical to use a javax.swing.Timer for triggering updates, rather than implementing Runnable (etc.)
    - Attempting to set the thread priority will throw a SecurityException, though oddly it occurs when attempting to set the Thread priority to maximum, whereas the earlier call to set the Thread priority to minimum passed without comment (exception).
    - The paint() method of that applet is not double buffered.
    - It is generally advisable to override paintComponent(Graphics) in a JPanel that is added to the top-level applet (or JFrame, or JWindow, or JDialog..) rather than the paint(Graphics) method of the top-level container itself.
    Edited by: AndrewThompson64 on Jan 22, 2010 12:47 PM

  • Double buffering && repaint

    Hi there,
    I have a frame F that contains two panels P1 and P2.
    P1 uses double buffering for drawing circles and lines.
    P2 has buttons and a JList.
    When i click on a JList to have popup menu
    or when i move the frame F on the screen
    the panel P2 lost some of JList drawing.
    Actually i iconify the frame in order to oblige
    JVM to do repaint.
    How can i resolve this problem please.

    Do not ever mix heavyweight and lightweight, or else
    you won't be able to set up the correct zorder.But when i iconfiy and desiconify my frame Java
    repaint correctly.
    I need a nice tip article of how to simulate
    desiconify repainting process.
    Thabk u

  • Double buffering circle not round

    I am making an applet where some circles are painted to the screen. When not using the double buffering scenario, the shapes appear correctly.
    The problem is when i use the double-buffering technique, the circles are still there, but they look like very ugly. I would call that some "squarcles".
    What is the bug here and how to get some decent double buffering with thoses circles?

    Here is the code so far i have that is used for painting on the screen:
    // Declaration
    private BufferedImage ecran;
    private Graphics2D buffer_ecran;
    // Instantiation
    this.ecran = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB);
    this.buffer_ecran = ecran.createGraphics();
    // In paint() method
    Graphics be = buffer_ecran;
      // Clean the surface
    be.setColor(Color.WHITE);
    be.fillRect(0, 0, getSize().width, getSize().height);
      // Draw the circles
    be.setColor(Color.RED);
    be.drawOval(x, y, ra, rb);
      // Output the buffer to the screen
    g.drawImage(ecran, 0, 0, this);I was previously using Image and changed to BufferedImage with the hope it would resolve the situation. I can't tell a significant change in image display.

  • Double buffering method - confusion

    Hello everyone,
    I've been messing around with Applets and animation in them and needed a method to reduce/remove flicker, so I decided on double buffering and looked up a tutorial on it. I understand the concept of it clearly, however the code doesn't make too much sense to me even after reading paint/graphics pages. What confuses me is:
    Why is the "g.drawString()" in update method if it already paints the dbg graphics? I commented it out, and the ball won't move. In addition, in the drawImage method it draws dbImage which is only altered once (see when it was null), so how are we using it to double buffer if we never write to it except once?
    import java.applet.*;
    import java.awt.*;
    public class BallBasic extends Applet implements Runnable {
        int x_pos = 10;
        int y_pos = 10;
        int radius = 20;
        private Image dbImage;
        private Graphics dbg;
        public void init() {
            setBackground(Color.blue);
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void stop() {
        public void destroy() {
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                x_pos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        public void update(Graphics g) {
            if (dbImage == null) {
                System.out.println("dbImage was null");
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            dbg.setColor(getForeground());
            paint(dbg);
            g.drawImage(dbImage, 0, 0, this);
        public void paint(Graphics g) {
            g.setColor(Color.red);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
    }Thanks for reading, hope you can help.
    Note: I understand how the panting process works, how it ties into update, ectcetera, please do not post explanations of how painting/applets work, just looking for heavy comments on what is happening throughout the update/paint method.

    Patrick_Ritchie wrote:
    I want to understand the concepts of this and how to use just plain ol' applets. I need to learn these things ;)Most people skip the old AWT. Did you learn how steam engines worked before you learned to drive a car?

  • Double Buffering Slow..is it in the code? or..

    Hi all..
    i make small application which use double buffering..
    here's the code:
    public void update(Graphics g){
            tys_a=System.currentTimeMillis();
            Dimension d = getSize();       
            if (offscreenImage == null || offscreenImage.getWidth(null) < d.width || offscreenImage.getHeight(null) < d.height){
                if (offscreenImage != null) offscreenImage.flush();
                offscreenImage = createImage(d.width, d.height);
                offscreenSize = d;
                offscreenGraphics = offscreenImage.getGraphics();
            offscreenGraphics.clearRect(0, 0, d.width, d.height);
            paint(offscreenGraphics);
            g.drawImage(offscreenImage, 0, 0, null);
            g.dispose();
            tys_b=System.currentTimeMillis();
            tys_c=tys_b-tys_a;
            System.out.println("DRAW OFFSCREEN GRAPH " + tys_c + " --- " + tys_a + " ---- " + tys_b);
        }then i run it on my desktop PC, which specs are
    Core 2 duo E4500 - 2.20Ghz, 2 Gb RAM , Vista Home Premium
    its works fine..took 10 ms
    but when i try on Sony vaio laptop, which specs are:
    core 2 duo T8100 - 2.1Gghz, 2Gb RAM, Vista home premium
    its so slow..took average about 800-900ms (80-90 times slower)
    did i do something wrong with my code...i've been searching all day...but seems no answer
    but all i can think..is not about the code..because it works fine in my desktop...
    but i dunno what cause this problem?
    any body can help?or ever have this kind of problem willing to share?
    Thx,

    AndrewThompson64 wrote:
    >
    Hi,
    dunnoIs this a English word???>Is this an English word? No it is not, it is strine* for "I do not know". I understand the Americans also know of this strine abbreviation, but I cannot understand how, since their comprehension of strine is quite low.
    * local pronunciation of 'Australian'.
    But to the OP. It is a far better idea to phrase your replies in standard English, since many people who understand English do not understand (or will not tolerate) local abbreviations and slang.In the South West of England It can be translated as "I don't know and I don't care" often accompanied by a shrug of the shoulders.

  • Properly (?) Double Buffered Applet is really Choppy

    Hi all. I looked around here for the proper way to double buffer an applet, and I think I've got it, but it's realllly choppy when it runs. (It's a little 2d jump 'n run game with not much in it yet). If you have any idea why, please tell =) Thanks!
    public class Game extends JApplet implements KeyListener, Runnable
         //doublebuffer stuff
         Graphics bufferGraphics;
         Image offscreenImage;
         Dimension dim;
         //constants
         int SCREEN_WIDTH = 800;
         int SCREEN_HEIGHT = 600;
         int SPRITE_SIZE = 64;
         Color BGColor = Color.white;
         int PLAYER_SPEED_X = 10;
         int PLAYER_JUMP_SPEED = 20;
         int GRAVITY_ACCEL = 1;
         //directional constants
         int LEFT = -1;
         int RIGHT = 1;
         int STOPPED = 0;
         int UP = -1;
         int DOWN = 1;
         //images
         Image playerImage;
         //movement
         boolean freeFall = true;
         int playerDirX = STOPPED;
         int playerVelY = 0;
         int playerPosX = 0;
         int playerPosY = 0;
         //game control variables
         boolean gameIsRunning = false;
         Thread t;
         int i = 0;
         public void init()
              addKeyListener(this);
              gameIsRunning = true;
              //prepare offscreen image for double buffering
              setSize(800,600);
              dim = getSize();
              offscreenImage = createImage(dim.width,dim.height);
              bufferGraphics = offscreenImage.getGraphics();
              playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
              t = new Thread(this);
              t.start();
         public void run()
              while(gameIsRunning)
                   try
                        t.sleep(33);
                   catch (InterruptedException e) {}
                   playerPosX += playerDirX*PLAYER_SPEED_X;
                   playerPosY -= playerVelY;
                   if(freeFall)
                        playerVelY -= GRAVITY_ACCEL;
                   //wraparound
                   if(playerPosX < 0)
                        playerPosX = 0;
                   if(playerPosX > SCREEN_WIDTH - SPRITE_SIZE)
                        playerPosX = SCREEN_WIDTH - SPRITE_SIZE;
                   //stop at the floor
                   if(playerPosY > SCREEN_HEIGHT - SPRITE_SIZE)
                        freeFall = false;
                        playerVelY = 0;
                        playerPosY = SCREEN_HEIGHT - SPRITE_SIZE;
                   repaint();
         public void keyPressed(KeyEvent e)
              //move right
              if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
                        e.getKeyCode() == KeyEvent.VK_D)
                   playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
                   playerDirX = RIGHT;
              //move left
              if(e.getKeyCode() == KeyEvent.VK_LEFT ||
                        e.getKeyCode() == KeyEvent.VK_A)
                   playerImage = getImage(getDocumentBase(),"images/playerLeft.gif");
                   playerDirX = LEFT;
              //jump
              if(e.getKeyCode() == KeyEvent.VK_SPACE ||
                        e.getKeyCode() == KeyEvent.VK_W ||
                        e.getKeyCode() == KeyEvent.VK_UP)
                   //allow jumping if we're standing on a surface
                   if(playerPosY == SCREEN_HEIGHT - SPRITE_SIZE ||
                             playerPosX == 0 ||
                             playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
                        if(playerPosX == 0)
                             playerDirX = RIGHT;
                             playerImage =
                                  getImage(getDocumentBase(),"images/playerRight.gif");
                        if(playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
                             playerDirX = LEFT;
                             playerImage =
                                  getImage(getDocumentBase(),"images/playerLeft.gif");
                        freeFall = true;
                        playerVelY = PLAYER_JUMP_SPEED;
         public void keyReleased(KeyEvent e)
              //stop moving right
              if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
                        e.getKeyCode() == KeyEvent.VK_D)
                   if(playerDirX == RIGHT)
                        playerDirX = STOPPED;
              //stop moving left
              if(e.getKeyCode() == KeyEvent.VK_LEFT ||
                        e.getKeyCode() == KeyEvent.VK_A)
                   if(playerDirX == LEFT)
                        playerDirX = STOPPED;
         public void keyTyped(KeyEvent e)
         public void paint(Graphics g)
              //clear screen
              bufferGraphics.setColor(Color.white);
              bufferGraphics.fillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
              //draw the player
              bufferGraphics.drawImage(playerImage,playerPosX,playerPosY,this);
              g.drawImage(offscreenImage,0,0,this);
         public void stop()
              t.stop();
        public void update(Graphics g)
             paint(g);
    }

    It looks fine to me, but don't reload the player images every time. If you need a different image you should read up on AffineTransform and do some rotations etc, or at least have the 4 images in an array or something.
    P.S. stop is deprecated for threads. If you are done with the thread null it. That being said, if you are making this as an applet, make sure you can restart or reload it properly by testing it with the appletvier.
    Good luck in your work.

  • Fine Tuning Java 1.1 Double Buffering?

    Dear Java gurus,
    Hi, I'm looking for suggestions on improving the performance of my double buffering technique for pure Java 1.1 applets.
    My current method seems to eat up more CPU & RAM than it should. I fear that real implementations (with far more drawing to the buffer before update), would be impractically slow and choke using double buffering the way I am now.
    I have programmed a simple applet demonstrating my current method (code below), which runs at 20 fps. I tried to keep it short and sweet.
    I'm only looking for pure Java 1.1 code.
    Thanks in advance. =)
    import java.awt.*;
    import java.applet.*;
    public class ColourFader extends Applet implements Runnable {
    // Class Variables
         int appletWidth = 600;
         int appletHeight = 300;
         int fps = 20;
         int delay = 1000 / fps;
         int nextRGB [] = {255, 0, 255};
         int currRGB [] = {0, 255, 0};
    // Class Objects
         Image offImage;
         Graphics offGraphics;
         Thread animator;
    // Applet Methods          
         public void start() {
              animator = new Thread(this);
              animator.start();
              offImage = createImage(appletWidth, appletHeight);
              offGraphics = offImage.getGraphics();
         public void stop() {
              animator = null;
              offImage = null;
              offGraphics = null;
         public void paint(Graphics g) {
              g.drawImage(offImage, 0, 0, null);
              update(g);
    // Runnable Method
         public void run() {
              while(Thread.currentThread() == animator) {
                   long tm = System.currentTimeMillis();
                   repaint();
                   try {
                        tm += delay;
                        Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                   } catch (InterruptedException e) {
                        break;
    // Convenience Methods
         public void update(Graphics g) {
              fadeRGBValues();
              paintFrame(offGraphics);
              g.drawImage(offImage, 0, 0, null);
         public void paintFrame(Graphics g) {
              g.setColor(new Color(currRGB[0], currRGB[1], currRGB[2]));
              g.fillRect(0, 0, appletWidth, appletHeight);          
         public void fadeRGBValues() {
              for(int i = 0; i <= 2; i++) {
                   if(currRGB[i] < nextRGB) {
                        currRGB[i] += 1;
                   } else if (currRGB[i] > nextRGB[i]) {
                        currRGB[i] -= 1;
                   } else {
                        nextRGB[i] = randomNum();
         public int randomNum() {
              double randomDouble = Math.random() * 255.0;
              int randomInt = (int) randomDouble;
              return(randomInt);

    Usually first update is called, then paint. In your paint method you call update, I don't see any reason for that. You want your paint method to be fast, so I would remove the update call.
    Instead I would call paint from the update method. Update is not needed to be called as often as the paint method. I think I would make the update method do nothing (just call the paint method). Then I would make another method I could call when I need to make some updates, and which did not take any graphics object as argument, becuase you dont need it.
    So something like this:
    public void update(Graphics g) {
      paint(g);
    public void paint(Graphics g) {
      g.drawImage(offImage, 0, 0, null);
    public void update() {
      fadeRGBValues();
      paintFrame(offGraphics); 
    }Then in your run method, just before repaint(), I would call update().
    Thread.sleep(0) would sleep forever I think. So be careful with that. A better way to do it:
    public void run() {
      long start = System.currentTimeMillis();
      int count = 0;
      while (Thread.currentThread() == animator) {
        update();
        repaint();
        count++;
        long sleep = count*delay-(System.currentTimeMillis()-start);
        if (sleep > 0) {
          try {
            Thread.sleep(sleep);
          } catch (InterruptedException e) {
            break;
    }

  • Panel refreshing and double buffering

    Hi all swing experts
    Could any one solve the problem.I have an application,which is having a JSplit pane.
    On the left of the JSplit pane , there is a tree. When u click a node from the tree
    that will be selected and you can place that node into the right side panel.
    And the same way you can click an another node (redirection or sink) and drop into the
    panel.you can draw a line by clicking the source and the sink / or redirection.
    The line is getting drawn dynamically by getting the x,y coordinates of the node.
    once the line is drawn am storing the line into vector, since this is getting drawn
    dynamically once if i minimize and maxmize it will disappear.
    For avoiding this am trying to redraw the old line from the vector when the window
    is getting activated, here the problem starts it draws the line but the line
    is getting disappeared immly.
    HOW DO I SOLVE THIS?
    is it possible to solve this problem with double buffering tech? if so how?
    PL HELP.
    Software - Visual Tool
    Last Modified -7/23/01
    sami
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.plaf.FontUIResource;
    import javax.swing.tree.*;
    import java.lang.System;
    import java.net.*;
    import java.awt.image.*;
    import javax.swing.event.*;
    public class CompTree extends JFrame implements TreeSelectionListener,WindowListener{      
    // Swing components declarations     
         public JSplitPane jSplitPane1,jSplitPaneTop;
         public JScrollPane treeScrollPane,splitScrollPane;     
    public JTree mainTree,jtree ;
    public static DefaultMutableTreeNode topchildnode1, topchildnode2, topchildnode3,toptreenode;
    DrawPanel dp = new DrawPanel();
         public int i=0;
         public int j=0;
         public int flag = 1 ;
         public String var,S,R,D;
    Frame fr = new Frame("GUI TOOL");
    public CompTree()
         File nFile = null ;     
         mainTree = DrawTree(nFile,"N") ;
         mainTree.updateUI();
         mainTree.setBackground(new Color(105,205,159));     
              // Tree is getting added into scroll pane
         treeScrollPane = new JScrollPane(mainTree);
              treeScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    treeScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              splitScrollPane = new JScrollPane();
              splitScrollPane.setViewportView(dp.panel1);          
              splitScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    splitScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jSplitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,treeScrollPane,splitScrollPane);          
         jSplitPane1.setOneTouchExpandable(true);
         jSplitPane1.setContinuousLayout(true);
    jSplitPane1.addComponentListener(new ComponentAdapter(){
              public void componentResized(ComponentEvent e) {      
                   System.out.println("Componenet resized");
              flag = 1;
              paint(dp.panel1.getGraphics());          
    //Provide minimum sizes for the two components in the split pane
    Dimension minimumSize = new Dimension(150,75);
              splitScrollPane.setMinimumSize(minimumSize);
    //Provide a preferred size for the split pane
    jSplitPane1.setPreferredSize(new Dimension(700, 500));
              //setContentPane(jSplitPane1);
              fr.add(jSplitPane1);
              fr.setSize(700,500);
              fr.setVisible(true);          
              fr.addWindowListener(this);     
    public void windowActivated(WindowEvent we){
         System.out.println("activated");
         dp.draw();
    public void windowClosed(WindowEvent we){System.out.println("closed");}
    public void windowIconified(WindowEvent we){System.out.println("iconified");}
    public void windowDeiconified(WindowEvent we){
         dp.draw();
         System.out.println("deiconified");
    public void windowDeactivated(WindowEvent we){System.out.println("deactivated");}
    public void windowOpened(WindowEvent we){
         dp.repaint();
         System.out.println("opened");
    public void windowClosing(WindowEvent we){
         System.exit(0);
         System.out.println("closing");
         public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)
              mainTree.getLastSelectedPathComponent();     
              String strRootNode = "" ;
              try{
                   Object rootNode = node.getRoot();          
                   strRootNode = rootNode.toString() ;
              catch(Exception eRoot)
                   System.out.println("Error in geting Root Node");
              if (node == null) return;
              Object nodeInfo = node.getUserObject();          
              TreeNode ParentNode = node.getParent();               
              final String strParentName = node.toString() ;
                   if (strParentName.equals("Source"))
              System.out.println("Before source");     
              var = "S";
              System.out.println("This is source");
              else if (strParentName.equals("Redirection"))
    var ="R";
              else if (strParentName.equals("Sink") )
                   var ="D";
              else
                   if ( strRootNode != strParentName){
         public JTree DrawTree( File file, String strIsValid)
                   jtree = new JTree();
                   toptreenode = new DefaultMutableTreeNode("Start");
                   topchildnode1 = new DefaultMutableTreeNode("Source");
                   topchildnode2 = new DefaultMutableTreeNode("Sink");
                   topchildnode3 = new DefaultMutableTreeNode("Redirection");
                   toptreenode.add(topchildnode1);
                   toptreenode.add(topchildnode2);
                   toptreenode.add(topchildnode3);
                   jtree.putClientProperty("JTree.lineStyle", "Angled");
                   DefaultTreeModel defaulttreemodel = new DefaultTreeModel(toptreenode);
                   jtree.setModel(defaulttreemodel);
                   DefaultTreeSelectionModel defaulttreeselectionmodel = new DefaultTreeSelectionModel();
                   defaulttreeselectionmodel.setSelectionMode(1);
                   jtree.setSelectionModel(defaulttreeselectionmodel);
                   jtree.addTreeSelectionListener(this);
                   jtree.setEditable(true);
                   return jtree;      
    public static void main(String args[]){
         CompTree ct = new CompTree();
         * This class contains all the component related to panel 1
         * this can be used for .....
    public class DrawPanel extends JPanel implements ActionListener,
         ComponentListener,MouseListener,KeyListener{
         public JRadioButton uniRadio,multiRadio,show;
         public JButton sBut,rBut,dBut;
         public int flag = 1 ;
         public int Radio = 1;
         public boolean sIndicator = true;
         public boolean rIndicator = true;
         public boolean isDestSelected = false;
         public boolean isDestFirstTime = true;
    public int x1 = 0 ;
         public int y1 = 0 ;
         public int x2 = 0 ;
         public int y2 = 0;
         public int x3 = 0;
         public int y3 = 0;
         public int k=0;
         public int l = 40;
    public int b = 40;     
         public String connection1,connection2,connection3,destination1,destination2;
         public int locX;
         public int locY;
    public JPanel panel1 = new JPanel ();      
    public JPanel panel2 = new JPanel ();     
         Vector lines = new Vector();
         Vector colors = new Vector();
         Vector obj = new Vector();
    Vector source = new Vector();
         Vector loc = new Vector();
         BasicStroke stroke = new BasicStroke(2.0f);
    Icon compImage = new ImageIcon("network1.gif"); //new
    Icon workImage = new ImageIcon("tconnect02.gif");
    Icon lapImage = new ImageIcon("server02.gif");
         public DrawPanel(){
         am adding radio button for checking the mode unicast and broad cast mode -- new
    uniRadio = new JRadioButton("Unicast Mode");
    uniRadio.setMnemonic(KeyEvent.VK_B);
    uniRadio.setSelected(true);
    multiRadio = new JRadioButton("Broadcast Mode");
    multiRadio.setMnemonic(KeyEvent.VK_C);
    show = new JRadioButton("show Panel");
    show.setMnemonic(KeyEvent.VK_C);
         ButtonGroup group = new ButtonGroup();
    group.add(uniRadio);
    group.add(multiRadio);
              group.add(show);
         /*     Border border = ButtonGroup.getBorder();
              Border margin = new EmptyBorder(10,10,10,10);
              ButtonGroup.setBorder(new CompoundBorder(border,margin)); */
              uniRadio.addActionListener(this);
         multiRadio.addActionListener(this);
              show.addActionListener(this);
    panel1.add(uniRadio);
              panel1.add(multiRadio);
              panel1.add(show);
              uniRadio.setBounds(150,15,100,40);
              multiRadio.setBounds(260,15,120,40);
              show.setBounds(390,15,100,40);
              uniRadio.setBackground(new Color(105,200,205));
              multiRadio.setBackground(new Color(105,200,205));
              show.setBackground(new Color(105,200,205));
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,100,205));
              panel1.addComponentListener(this);
              panel1.addMouseListener(this);      
         public void sourceObject(String name)
    sBut = new JButton(compImage);
         panel1.add(sBut);     
         sBut.setMnemonic(KeyEvent.VK_F);
         sBut.setBounds(new Rectangle(locX,locY,l,b));     
         sBut.addActionListener(this);
         sBut.addMouseListener(this);
         sBut.addKeyListener(this);
    System.out.println("am inside the source object") ;
         sBut.setBackground(new Color(105,100,205));
         System.out.println("key number" +sBut.getMnemonic());
         System.out.println("MY LOCATION : SBUT : "+ sBut.getLocation());
         public void redirectionObject(String name)
         rBut = new JButton(workImage);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(locX,locY,l,b));     
    rBut.addActionListener(this);
         rBut.addMouseListener(this);
         rBut.addKeyListener(this);
         rBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the redirection :" + j) ;
    System.out.println("MY LOCATION : RBUT : "+ rBut.getLocation());          
    public void destinationObject(String name){     
         dBut = new JButton(lapImage);
         panel1.add(dBut);     
         dBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the destination object") ;     
    dBut.setBounds(new Rectangle(locX,locY,l,b));                    
         System.out.println("am inside the destination:" + j) ;
         dBut.addActionListener(this);
         dBut.addMouseListener(this);
         dBut.addKeyListener(this);
         System.out.println("MY LOCATION : DBUT : "+ dBut.getLocation());           
    public void paintComponent(Graphics g){
    super.paintComponent(g);
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(stroke);
    if(flag == 1){
         /* this is for drawing current line, this will be drawn when component event happens */
              g.setColor(getForeground());
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println("Total number of lines present the buffer to draw :" + np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                        g2.setColor((Color)colors.elementAt(I));
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                        //     g2.setPaint(p.x,p.y,p.width,p.height);
                             g2.drawLine(p.x,p.y,p.width,p.height);                         
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(obj.elementAt(I));
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(p.x +"," +","+ p.y + ","+ ","+ p.width+ "," + ","+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    connection1 = "source to redirection";
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);          
         lines.addElement(new Rectangle(x1,y1,x2,y2));
         colors.addElement(getForeground());
         obj.addElement(connection1);
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              connection2 = "Redirection to Destination";
              g2.setColor(Color.green);
                   g2.drawLine(x2,y2,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x2,y2,x3,y3));               
                   obj.addElement(connection2);
                   x2 = 0; y2 = 0 ;
                   x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   connection3 = "Source to Destination";
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                   obj.addElement(connection3);
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
                        /*     Image offscreen = panel1.createImage(400,400);
              Graphics og = offscreen.getGraphics();
         og.drawLine(200,200,500,500);
              g.drawImage(offscreen,0,0,null); */
    // Component Listener's method
    public void componentHidden(ComponentEvent e) { 
    if(e.getSource().equals(panel1)){System.out.println("Componenet Hidden");}
              System.out.println("Componenet Hidden");
    public void componentMoved(ComponentEvent e) {
              System.out.println("Componenet moved");
              draw();
    public void componentResized(ComponentEvent e) {      
              System.out.println("Componenet resized");
              flag = 1;
              paintComponent(panel1.getGraphics());
    public void componentShown(ComponentEvent e) {     
              System.out.println("Componenet Shown");
    // Mouse Listerner's Method
         public void mouseClicked(MouseEvent me){
    if (me.getSource().equals(panel1))
              System.out.println("inside mouse clicked");
                        if(var == "S"){
    the boolean sIndicator will allow the usage of source object only once
         This is the case for both unicast and multi cast.It has been restricted
         to single use.
                             if (sIndicator){
                             System.out.println("inside mouse clicked");
                        System.out.println("locX" + locX);
                        locX = me.getX();
    locY = me.getY();
                   sourceObject("Source");
                             sIndicator = false;
                        }else{}
              }else if (var == "R")
    if(rIndicator){
    if(!isDestSelected){
    System.out.println("redirection" + locX);
    locX = me.getX();
    locY = me.getY();
                   redirectionObject("Redirection");
                   rIndicator = false;
                   }else{}
    } else{}
              }else if(var == "D"){
              if(Radio == 1 && isDestSelected == false){
              System.out.println("Destination -- uni cast mode" + locX);
    locX = me.getX();
    locY = me.getY();
                   destinationObject("Sink");
              isDestSelected = true;
              } else if (Radio == 2)
                                  System.out.println("Destination -- Multicast mode" + locX);
                                  locX = me.getX();
                                  locY = me.getY();
                                  destinationObject("Sink");
                                  isDestSelected = true;                    
         public void mousePressed(MouseEvent me){System.out.println("am inside mouse pressed"); }
         public void mouseReleased(MouseEvent me){
              System.out.println("am inside mouse released");
              paintComponent(panel1.getGraphics());
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
    // key Listener
    public void keyReleased(KeyEvent e) {        
                        Component compo =(JButton)e.getSource();                               
                             if (e.getKeyChar() == e.VK_DELETE){                         
                             remove(compo);
              public void keyTyped(KeyEvent e) {}
              public void keyPressed(KeyEvent e){}
    public void remove(Component comp){          
    System.out.println("inside delete key" );                         
         panel1.remove(comp);
         panel1.repaint();     
         public void draw(){
              super.paint(panel1.getGraphics());
              System.out.println("inside draw");
              flag = 1;
              paintComponent(panel1.getGraphics());     
         public void actionPerformed(ActionEvent e)
                             if(e.getSource().equals(sBut)){
                                  System.out.println("am s button");                
                                  x1 = sBut.getX() + l;
                                  y1 = sBut.getY() + (b/2);
                             else if(e.getSource().equals(rBut)){
                                  System.out.println("am r button");               
                                  x2 = rBut.getX() ;
                                  y2 = rBut.getY()+ b/2;
                                  System.out.println("x2 : " + x2 + "y2 :" +y2 );
                             else if(e.getSource().equals(dBut)){
                                  System.out.println("am d button");                
                                  x3 = dBut.getX();
                                  y3 = dBut.getY()+ b/2;
                             else if (e.getSource().equals(uniRadio)){
                                  System.out.println("uni radio");
                                  Radio = 1 ;
                             } else if (e.getSource().equals(multiRadio)){
                                       System.out.println("multi radio");
                                       Radio = 2;
                             } else if (e.getSource().equals(show)){            
                                  System.out.println("inside show");
    *********************************************

    ok
    i don't take a long time tracing your code, but i think u have to overwrite the repaint methode so it 's call the methode which will paint the line each time.
    hope this will help!

Maybe you are looking for