Repaint canvas

How can I send repaint event to Canvas object?

If you are trying to restrict it to only Canvas objects:
1) Make a linked list and as you add the canvases to your GUI, add them to the list. Later, run through the list to repaint.
2) Get all the children components from your top level component and recursively search for all Canvases to repaint.

Similar Messages

  • Overlay Images and Shapes on the same canvas

    The example copde below was taken from: http://math.hws.edu/eck/cs124/javanotes3/source/
    Is it possible to update the code so that images (jpg,gif) can be added as well as shapes?
    Any help with this is much appreciated.
        The ShapeDraw applet lets the user add small colored shapes to
        a drawing area and then drag them around.  The shapes are rectangles,
        ovals, and roundrects.  The user adds a shape to the canvas by
        clicking on a button.  The shape is added at the upper left corner
        of the canvas.  The color of the shape is given by the current
        setting of a pop-up menu.  The user can drag the shapes with the
        mouse.  Ordinarily, the shapes maintain a given back-to-front order.
        However, if the user shift-clicks on a shape, that shape will be
        brought to the front.
        A menu can be popped up on a shape (by right-clicking or performing
        some othe platform-dependent action).  This menu allows the user
        to change the size and color of a shape.  It is also possible to
        delete the shape and to bring it to the front.
        This file defines the applet class plus several other classes used
        by the applet, namely:  ShapeCanvas, Shape, RectShape, OvalShape,
        and RoundRectShape.
        David Eck
        July 28,  1998
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.util.Vector;
    public class ShapeDrawWithMenu extends Applet {
       public void init() { 
            // Set up the applet's GUI.  It consists of a canvas, or drawing area,
            // plus a row of controls below the canvas.  The controls include three
            // buttons which are used to add shapes to the canvas and a Choice menu
            // that is used to select the color used for a shape when it is created.
            // The canvas is set as the "listener" for these controls so that it can
            // respond to the user's actions.  (The pop-up menu is created by the canvas.)
          setBackground(Color.lightGray);
          ShapeCanvas canvas = new ShapeCanvas();  // create the canvas
          Choice colorChoice = new Choice();  // color choice menu
          colorChoice.add("Red");
          colorChoice.add("Green");
          colorChoice.add("Blue");
          colorChoice.add("Cyan");
          colorChoice.add("Magenta");
          colorChoice.add("Yellow");
          colorChoice.add("Black");
          colorChoice.add("White");
          colorChoice.addItemListener(canvas);
          Button rectButton = new Button("Rect");    // buttons for adding shapes
          rectButton.addActionListener(canvas);
          Button ovalButton = new Button("Oval");
          ovalButton.addActionListener(canvas);
          Button roundRectButton = new Button("RoundRect");
          roundRectButton.addActionListener(canvas);
          Panel bottom = new Panel();   // a Panel to hold the control buttons
          bottom.setLayout(new GridLayout(1,4,3,3));
          bottom.add(rectButton);
          bottom.add(ovalButton);
          bottom.add(roundRectButton);
          bottom.add(colorChoice);
          setLayout(new BorderLayout(3,3));
          add("Center",canvas);              // add canvas and controls to the applet
          add("South",bottom);
       public Insets getInsets() {
            // Says how much space to leave between the edges of the applet and the
            // components in the applet.
          return new Insets(3,3,3,3);
    }  // end class ShapeDraw
    class ShapeCanvas extends Canvas implements ActionListener, ItemListener,
                                                MouseListener, MouseMotionListener {
          // This class represents a canvas that can display colored shapes and
          // let the user drag them around.  It uses an off-screen images to
          // make the dragging look as smooth as possible.  A pop-up menu is
          // added to the canvas that can be used to performa certain actions
          // on the shapes;
       Image offScreenCanvas = null;   // off-screen image used for double buffering
       Graphics offScreenGraphics;     // graphics context for drawing to offScreenCanvas
       Vector shapes = new Vector();   // holds a list of the shapes that are displayed on the canvas
       Color currentColor = Color.red; // current color; when a shape is created, this is its color
       ShapeCanvas() {
            // Constructor: set background color to white, set up listeners to respond to mouse actions,
            //              and set up the pop-up menu
          setBackground(Color.white);
          addMouseListener(this);
          addMouseMotionListener(this);
          popup = new PopupMenu();
          popup.add("Red");
          popup.add("Green");
          popup.add("Blue");
          popup.add("Cyan");
          popup.add("Magenta");
          popup.add("Yellow");
          popup.add("Black");
          popup.add("White");
          popup.addSeparator();
          popup.add("Big");
          popup.add("Medium");
          popup.add("Small");
          popup.addSeparator();
          popup.add("Delete");
          popup.add("Bring To Front");
          add(popup);
          popup.addActionListener(this);
       } // end construtor
       synchronized public void paint(Graphics g) {
            // In the paint method, everything is drawn to an off-screen canvas, and then
            // that canvas is copied onto the screen.
          makeOffScreenCanvas();
          g.drawImage(offScreenCanvas,0,0,this);
       public void update(Graphics g) {
            // Update method is called when canvas is to be redrawn.
            // Just call the paint method.
          paint(g);
       void makeOffScreenCanvas() {
             // Erase the off-screen canvas and redraw all the shapes in the list.
             // (First, if canvas has not yet been created, then create it.)
          if (offScreenCanvas == null) {
             offScreenCanvas = createImage(getSize().width,getSize().height);
             offScreenGraphics = offScreenCanvas.getGraphics();
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
          int top = shapes.size();
          for (int i = 0; i < top; i++) {
             Shape s = (Shape)shapes.elementAt(i);
             s.draw(offScreenGraphics);
       public void itemStateChanged(ItemEvent evt) {
              // This is called to respond to item events.  Such events
              // can only be sent by the color choice menu,
              // so respond by setting the current color according to
              // the selected item in that menu.
          Choice colorChoice = (Choice)evt.getItemSelectable();
          switch (colorChoice.getSelectedIndex()) {
             case 0: currentColor = Color.red;     break;
             case 1: currentColor = Color.green;   break;
             case 2: currentColor = Color.blue;    break;
             case 3: currentColor = Color.cyan;    break;
             case 4: currentColor = Color.magenta; break;
             case 5: currentColor = Color.yellow;  break;
             case 6: currentColor = Color.black;   break;
             case 7: currentColor = Color.white;   break;
       public void actionPerformed(ActionEvent evt) {
              // Called to respond to action events.  The three shape-adding
              // buttons have been set up to send action events to this canvas.
              // Respond by adding the appropriate shape to the canvas.  This
              // also be a command from a pop-up menu.
          String command = evt.getActionCommand();
          if (command.equals("Rect"))
             addShape(new RectShape());
          else if (command.equals("Oval"))
             addShape(new OvalShape());
          else if (command.equals("RoundRect"))
             addShape(new RoundRectShape());
          else
             doPopupMenuCommand(command);
       synchronized void addShape(Shape shape) {
              // Add the shape to the canvas, and set its size/position and color.
              // The shape is added at the top-left corner, with size 50-by-30.
              // Then redraw the canvas to show the newly added shape.
          shape.setColor(currentColor);
          shape.reshape(3,3,50,30);
          shapes.addElement(shape);
          repaint();
       // ------------ This rest of the class implements dragging and the pop-up menu ---------------------
       PopupMenu popup;
       Shape selectedShape = null;     // This is null unless a menu has been popped up on this shape.
       Shape draggedShape = null;      // This is null unless a shape has been selected for dragging.
       int prevDragX;  // During dragging, these record the x and y coordinates of the
       int prevDragY;  //    previous position of the mouse.
       Shape clickedShape(int x, int y) {
             // Find the frontmost shape at coordinates (x,y); return null if there is none.
          for ( int i = shapes.size() - 1; i >= 0; i-- ) {  // check shapes from front to back
             Shape s = (Shape)shapes.elementAt(i);
             if (s.containsPoint(x,y))
                return s;
          return null;
       void doPopupMenuCommand(String command) {
             // Handle a command from the pop-up menu.
          if (selectedShape == null)  // should be impossible
             return;
          if (command.equals("Red"))
             selectedShape.setColor(Color.red);
          else if (command.equals("Green"))
             selectedShape.setColor(Color.green);
          else if (command.equals("Blue"))
             selectedShape.setColor(Color.blue);
          else if (command.equals("Cyan"))
             selectedShape.setColor(Color.cyan);
          else if (command.equals("Magenta"))
             selectedShape.setColor(Color.magenta);
          else if (command.equals("Yellow"))
             selectedShape.setColor(Color.yellow);
          else if (command.equals("Black"))
             selectedShape.setColor(Color.black);
          else if (command.equals("White"))
             selectedShape.setColor(Color.white);
          else if (command.equals("Big"))
             selectedShape.resize(75,45);
          else if (command.equals("Medium"))
             selectedShape.resize(50,30);
          else if (command.equals("Small"))
             selectedShape.resize(25,15);
          else if (command.equals("Delete"))
             shapes.removeElement(selectedShape);
          else if (command.equals("Bring To Front")) {
             shapes.removeElement(selectedShape);
             shapes.addElement(selectedShape);
          repaint();
       synchronized public void mousePressed(MouseEvent evt) {
             // User has pressed the mouse.  Find the shape that the user has clicked on, if
             // any.  If there is a shape at the position when the mouse was clicked, then
             // start dragging it.  If the user was holding down the shift key, then bring
             // the dragged shape to the front, in front of all the other shapes.
          int x = evt.getX();  // x-coordinate of point where mouse was clicked
          int y = evt.getY();  // y-coordinate of point
          if (evt.isPopupTrigger()) {            // If this is a pop-up menu event that
             selectedShape = clickedShape(x,y);  // occurred over a shape, record which shape
             if (selectedShape != null)          // it is and show the menu.
                popup.show(this,x,y);
          else {
             draggedShape = clickedShape(x,y);
             if (draggedShape != null) {
                prevDragX = x;
                prevDragY = y;
                if (evt.isShiftDown()) {                 // Bring the shape to the front by moving it to
                   shapes.removeElement(draggedShape);  //       the end of the list of shapes.
                   shapes.addElement(draggedShape);
                   repaint();  // repaint canvas to show shape in front of other shapes
       synchronized public void mouseDragged(MouseEvent evt) {
              // User has moved the mouse.  Move the dragged shape by the same amount.
          if (draggedShape != null) {
             int x = evt.getX();
             int y = evt.getY();
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
       synchronized public void mouseReleased(MouseEvent evt) {
              // User has released the mouse.  Move the dragged shape, then set
              // shapeBeingDragged to null to indicate that dragging is over.
              // If the shape lies completely outside the canvas, remove it
              // from the list of shapes (since there is no way to ever move
              // it back onscreen).
          int x = evt.getX();
          int y = evt.getY();
          if (draggedShape != null) {
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height ||
                     draggedShape.left + draggedShape.width < 0 ||
                     draggedShape.top + draggedShape.height < 0 ) {  // shape is off-screen
                shapes.removeElement(draggedShape);  // remove shape from list of shapes
             draggedShape = null;
             repaint();
          else if (evt.isPopupTrigger()) {        // If this is a pop-up menu event that
             selectedShape = clickedShape(x,y);   // occurred over a shape, record the
             if (selectedShape != null)           // shape and show the menu.
                popup.show(this,x,y);
       public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
       public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
       public void mouseMoved(MouseEvent evt) { }
       public void mouseClicked(MouseEvent evt) { }
    }  // end class ShapeCanvas
    abstract class Shape {
          // A class representing shapes that can be displayed on a ShapeCanvas.
          // The subclasses of this class represent particular types of shapes.
          // When a shape is first constucted, it has height and width zero
          // and a default color of white.
       int left, top;      // Position of top left corner of rectangle that bounds this shape.
       int width, height;  // Size of the bounding rectangle.
       Color color = Color.white;  // Color of this shape.
       void reshape(int left, int top, int width, int height) {
             // Set the position and size of this shape.
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
       void resize(int width,int height) {
             // Set the size without changing the position
          this.width = width;
          this.height = height;
       void moveTo(int x, int y) {
              // Move upper left corner to the point (x,y)
          this.left = x;
          this.top = y;
       void moveBy(int dx, int dy) {
              // Move the shape by dx pixels horizontally and dy pixels veritcally
              // (by changing the position of the top-left corner of the shape).
          left += dx;
          top += dy;
       void setColor(Color color) {
              // Set the color of this shape
          this.color = color;
       boolean containsPoint(int x, int y) {
             // Check whether the shape contains the point (x,y).
             // By default, this just checks whether (x,y) is inside the
             // rectangle that bounds the shape.  This method should be
             // overridden by a subclass if the default behaviour is not
             // appropriate for the subclass.
          if (x >= left && x < left+width && y >= top && y < top+height)
             return true;
          else
             return false;
       abstract void draw(Graphics g); 
             // Draw the shape in the graphics context g.
             // This must be overriden in any concrete subclass.
    }  // end of class Shape
    class RectShape extends Shape {
          // This class represents rectangle shapes.
       void draw(Graphics g) {
          g.setColor(color);
          g.fillRect(left,top,width,height);
          g.setColor(Color.black);
          g.drawRect(left,top,width,height);
    class OvalShape extends Shape {
           // This class represents oval shapes.
       void draw(Graphics g) {
          g.setColor(color);
          g.fillOval(left,top,width,height);
          g.setColor(Color.black);
          g.drawOval(left,top,width,height);
       boolean containsPoint(int x, int y) {
             // Check whether (x,y) is inside this oval, using the
             // mathematical equation of an ellipse.
          double rx = width/2.0;   // horizontal radius of ellipse
          double ry = height/2.0;  // vertical radius of ellipse
          double cx = left + rx;   // x-coord of center of ellipse
          double cy = top + ry;    // y-coord of center of ellipse
          if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
             return true;
          else
            return false;
    class RoundRectShape extends Shape {
           // This class represents rectangle shapes with rounded corners.
           // (Note that it uses the inherited version of the
           // containsPoint(x,y) method, even though that is not perfectly
           // accurate when (x,y) is near one of the corners.)
       void draw(Graphics g) {
          g.setColor(color);
          g.fillRoundRect(left,top,width,height,width/3,height/3);
          g.setColor(Color.black);
          g.drawRoundRect(left,top,width,height,width/3,height/3);
    }

    Manveer-Singh
    Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this 3 year old thread now.
    db
    edit You have earlier been advised not to post in old dead threads.
    [http://forums.sun.com/thread.jspa?threadID=354443]
    Continuing to ignore this advice will render your account liable to be blocked.
    Edited by: Darryl.Burke

  • Can anyone point the errors made on my code?

    I want to write a java Applet that implements a Graphical User Interface(GUI) from the the AWT package(not SWING package) to display a Pie Chart. The program should read a string from the user, then determine and display a Pie Chart that represents the percentage of vowels(a,e,i,o,u), consonants and others lettres in that string.
    This is just the interface design. I get an error where i set up the border for the TextArea, and I can only get the button and the TextArea to display is I add the "South" and "North" respectively, while the recganglt won't even show up. Why? Anyone?
    import java.util.*;
    import java.awt.*;
    import java.awt.Graphics.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class PieChart extends Applet implements ActionListener
         private PieCanvas canvas;
         Button pro;
         Panel buttonPanel;
         Color back, colorV, colorC, colorO;
         String c1, c2, c3;
         public void init()
              String in =getParameter("background");
              c1 =getParameter("vowelColor");
              c2 =getParameter("consonantColor");
              c3 =getParameter("otherColor");
              back =Color.black;
              colorV = Color.red;
              colorC = Color.yellow;
              colorO = Color.green;
              if(in!=null)
              back =Color.decode(in);
              setLayout(new BorderLayout());
              setBackground(back);
              canvas =new PieCanvas();
              buttonPanel =new Panel();
              setLayout(new BorderLayout());
              pro =new Button("Process");
              buttonPanel.add(pro);
              pro.addActionListener(this);
              JTextArea textArea =new JTextArea("This is an editable JTextArea " + "that has been initialized with the setText method. " +
                   "A text area is a \"plain\" text component, " +
                   "which means that although it can display text " + "in any font, all of the text is in the same font.", 5, 40);
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
              textArea.setLineWrap(true);
              textArea.setWrapStyleWord(true);
              JScrollPane areaScrollPane =new JScrollPane(textArea);
              areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              areaScrollPane.setPreferredSize(new Dimension(10, 50));
              areaScrollPane.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED));
              add("North", textArea);
              add("Center", canvas);
              add("South", buttonPanel);
         /*public void actionPerformed(ActionEvent event)
              if(event.getSource()==pro)
                   canvas.repaint();
                   canvas.shape="rect";
                   canvas.shapename="A Rectangle...";
                   canvas.shapecolor=c1;
    class PieCanvas extends Canvas
         public String shape="";
         public String shapename="";
         public String shapecolor="";
         public final int MAX_WIDTH = 300;
         public void paint(Graphics g)
              g.drawRoundRect(70,10,70,50,20,7);
              /*int x, y;
              if(shape.equals("rect"))
                   if(shapecolor!=null)
                        g.setColor(Color.decode(shapecolor));
                   else
                   g.setColor(Color.blue);
                   g.drawRect(MAX_WIDTH/4, MAX_WIDTH/4, MAX_WIDTH/2, MAX_WIDTH/4);
                   g.setColor(Color.white);
                   g.drawString(shapename, MAX_WIDTH/4, MAX_WIDTH/8);*/
    }

    Okay, let's go through Error Identification for Dummies.
    1. Compile the program. Does this produce error messages? If so, what are they?
    2. Run the program. Does this throw exceptions? If so, what are they? Post the stack trace.
    3. If it runs without exception, does it do what you want it to do? If not, what did you want and what did it do? Be precise.

  • Rotate dragged shape on button click

    Hi guys,
    I need help here. I want to do a drawing application where user can resize and rotate a shape. I have created a shape which I can drag around but how to make it rotate upon clicking on button?? Let say when I select the shape and click on 'rotate' button my shape will be rotate by 90 degree. After that the rotated shape can still be drag. Any help would be appreciated.

    Hi Darryl.Burke,
    Thanks for your reply, yes I use AffineTransform methods to rotate the shape. Is there any different with other rotation method?? Ok when I use setToRotation, the shape indeed rotate to the correct position but when I click the shape return back to its original and other weird things happen. Below is the code. Can you please point out the part that I done it wrong please. Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.border.CompoundBorder;
    import java.io.*;
    public class RotateShape
         private static void createAndShowGUI() {
            //Create and set up the window.
           JFrame.setDefaultLookAndFeelDecorated(true);      
           Viewer frame = new Viewer();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setVisible(true);
        public static void main(String[] args)
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
    class Viewer extends JFrame implements ActionListener
         JMenuBar menuBar;
         drawRect buildDesign;
        public Viewer()
           Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int screenHeight = screenSize.height;
            int screenWidth = screenSize.width;
            // center frame in screen
              setSize(700, 600);
              setLocation(screenWidth / 4, screenHeight / 4);
              setResizable(false);
            buildDesign = new drawRect();
            buildDesign.setBorder(BorderFactory.createEmptyBorder(0, 2, 3, 3));
            JTabbedPane tabbed = new JTabbedPane();
            tabbed.addTab("Design", buildDesign);
            //tabbed.addTab("Viewer", buildViewer());
            tabbed.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                tabbed.getBorder()));
            //------------------------End of Tabbed Pane----------------------------------------------------//
          JPanel pane = new JPanel();
          Button rectButton = new Button("Rect");
          rectButton.addActionListener(this);
          pane.add(rectButton);
          Button deleteButton = new Button("Delete");
          deleteButton.addActionListener(this);
          pane.add(deleteButton);
          Button rotateButton = new Button("Rotate");
          rotateButton.addActionListener(this);
          pane.add(rotateButton);
          JScrollPane scroller = new JScrollPane(pane);
          scroller.setOpaque(false);
          scroller.getViewport().setOpaque(false);
          scroller.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                  scroller.getBorder()));
               //------------------------End of Build Item list----------------------------------------------//
          JPanel content = new JPanel(new BorderLayout());
          content.setOpaque(false);
          content.add(tabbed, BorderLayout.CENTER);
          content.add(scroller, BorderLayout.WEST);
          add (content, BorderLayout.CENTER);
          //------------------------End of add content----------------------------------------------//
              public void actionPerformed(ActionEvent evt) {
               // Respond to a command from one of the window's menu.
          String command = evt.getActionCommand();
          if (command.equals("Rect"))
             buildDesign.addShape(new RectShape());
          else if (command.equals("Delete"))
             buildDesign.delete();
          else if (command.equals("Rotate"))
             buildDesign.rotate();
    class drawRect extends JPanel implements ActionListener, MouseListener, MouseMotionListener
             Image offScreenCanvas = null;   // off-screen image used for double buffering
                 Graphics offScreenGraphics;     // graphics context for drawing to offScreenCanvas
                 Vector shapes = new Vector();   // holds a list of the shapes that are displayed on the canvas
                 Color currentColor = Color.black; // current color; when a shape is created, this is its color
                 float alpha;
            drawRect() {
            // Constructor: set background color to white set up listeners to respond to mouse actions
          setBackground(Color.white);
          addMouseListener(this);
          addMouseMotionListener(this);
       synchronized public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            // In the paint method, everything is drawn to an off-screen canvas, and then
            // that canvas is copied onto the screen.
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
          makeOffScreenCanvas();
          g2.drawImage(offScreenCanvas,0,0,this); 
          AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OUT,alpha);
              g2.setComposite(composite);
          g2.setColor(Color.GRAY);
          drawGrid(g, 20); 
       public void update(Graphics g) {
            // Update method is called when canvas is to be redrawn.
            // Just call the paint method.
          super.paintComponent(g);
       void makeOffScreenCanvas() {
             // Erase the off-screen canvas and redraw all the shapes in the list.
             // (First, if canvas has not yet been created, then create it.)
          if (offScreenCanvas == null) {
             offScreenCanvas = createImage(getSize().width,getSize().height);
             offScreenGraphics = offScreenCanvas.getGraphics();
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
          int top = shapes.size();
          for (int i = 0; i < top; i++) {
             Shape s = (Shape)shapes.elementAt(i);
             s.draw(offScreenGraphics);
            private void drawGrid(Graphics g, int gridSpace) {
          Insets insets = getInsets();
          int firstX = insets.left;
          int firstY = insets.top;
          int lastX = getWidth() - insets.right;
          int lastY = getHeight() - insets.bottom;
          //Draw vertical lines.
          int x = firstX;
          while (x < lastX) {
            g.drawLine(x, firstY, x, lastY);
            x += gridSpace;
          //Draw horizontal lines.
          int y = firstY;
          while (y < lastY) {
            g.drawLine(firstX, y, lastX, y);
            y += gridSpace;
        public void actionPerformed(ActionEvent evt)
         synchronized void addShape(Shape shape) {
              // Add the shape to the canvas, and set its size/position and color.
              // The shape is added at the top-left corner, with size 50-by-30.
              // Then redraw the canvas to show the newly added shape.
          shape.setColor(Color.red);
          shape.setColor(currentColor);
           shape.reshape(3,3,70,10);
          shapes.addElement(shape);
          repaint();
         void clear() {
             // remove all shapes
           shapes.setSize(0);
           repaint();
        void delete() {
             // remove selected shapes
                  shapes.removeElement(selectedShape);
                   repaint();
       void rotate() {     
                     //shapes.addElement(selectedShape);
                  selectedShape.setToRotate(true);
                  //shapes.removeElement(selectedShape);
                   repaint();
       Shape selectedShape = null;
       Shape shapeBeingDragged = null;  // This is null unless a shape is being dragged.
                                        // A non-null value is used as a signal that dragging
                                        // is in progress, as well as indicating which shape
                                        // is being dragged.
       int prevDragX;  // During dragging, these record the x and y coordinates of the
       int prevDragY;  //    previous position of the mouse.
        Shape clickedShape(int x, int y) {
             // Find the frontmost shape at coordinates (x,y); return null if there is none.
          for ( int i = shapes.size() - 1; i >= 0; i-- ) {  // check shapes from front to back
             Shape s = (Shape)shapes.elementAt(i);
             if (s.containsPoint(x,y))
                  s.tickSelected(true);
                  selectedShape = s;
                return s;
                else
                s.tickSelected(false);
                repaint();
          return null;
       synchronized public void mousePressed(MouseEvent evt) {
             // User has pressed the mouse.  Find the shape that the user has clicked on, if
             // any.  If there is a shape at the position when the mouse was clicked, then
             // start dragging it.  If the user was holding down the shift key, then bring
             // the dragged shape to the front, in front of all the other shapes.
          int x = evt.getX();  // x-coordinate of point where mouse was clicked
          int y = evt.getY();  // y-coordinate of point                                  
             shapeBeingDragged = clickedShape(x,y);
             if (shapeBeingDragged != null) {
                prevDragX = x;
                prevDragY = y;
                if (evt.isShiftDown()) {                 // Bring the shape to the front by moving it to
                   shapes.removeElement(shapeBeingDragged);  //       the end of the list of shapes.
                   shapes.addElement(shapeBeingDragged);
                   repaint();  // repaint canvas to show shape in front of other shapes
       synchronized public void mouseDragged(MouseEvent evt) {
              // User has moved the mouse.  Move the dragged shape by the same amount.
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
       synchronized public void mouseReleased(MouseEvent evt) {
              // User has released the mouse.  Move the dragged shape, then set
              // shapeBeingDragged to null to indicate that dragging is over.
              // If the shape lies completely outside the canvas, remove it
              // from the list of shapes (since there is no way to ever move
              // it back onscreen).
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
                     shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
                     shapeBeingDragged.top + shapeBeingDragged.height < 0 ) {  // shape is off-screen
                shapes.removeElement(shapeBeingDragged);  // remove shape from list of shapes
             shapeBeingDragged = null;
             repaint();
       public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
       public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
       public void mouseMoved(MouseEvent evt) { }
       public void mouseClicked(MouseEvent evt) { }
       abstract class Shape implements Serializable{
          // A class representing shapes that can be displayed on a ShapeCanvas.
          // The subclasses of this class represent particular types of shapes.
          // When a shape is first constucted, it has height and width zero
          // and a default color of white.
       int left, top;      // Position of top left corner of rectangle that bounds this shape.
       int width, height;  // Size of the bounding rectangle.
       Color color = Color.white;  // Color of this shape.
       boolean isSelected;
       boolean isRotate;
       AffineTransform t;
       AffineTransform origTransform;
       void reshape(int left, int top, int width, int height) {
             // Set the position and size of this shape.
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
       void moveTo(int x, int y) {
              // Move upper left corner to the point (x,y)
          this.left = x;
          this.top = y;
       void moveBy(int dx, int dy) {
              // Move the shape by dx pixels horizontally and dy pixels veritcally
              // (by changing the position of the top-left corner of the shape).
          left += dx;
          top += dy;
       void setColor(Color color) {
              // Set the color of this shape
          this.color = color;
       void tickSelected (boolean draw) {
                 // If true, a red outline is drawn around this shape.
             isSelected = draw;
       void setToRotate (boolean draw) {
                 // If true, the shape will rotate 90 deg
             isRotate = draw;
       boolean containsPoint(int x, int y) {
             // Check whether the shape contains the point (x,y).
             // By default, this just checks whether (x,y) is inside the
             // rectangle that bounds the shape.  This method should be
             // overridden by a subclass if the default behaviour is not
             // appropriate for the subclass.
          if (x >= left && x < left+width && y >= top && y < top+height)
             return true;
          else
                      return false;
       abstract void draw(Graphics g); 
             // Draw the shape in the graphics context g.
             // This must be overriden in any concrete subclass.
         }  // end of class Shape
    class RectShape extends Shape {
          // This class represents rectangle shapes.
       void draw(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            Rectangle2D wall = new Rectangle2D.Double(left,top,width,height);
            Rectangle2D border = new Rectangle2D.Double(left-2,top-2,width+3,height+3);
            origTransform = g2.getTransform();
            if ((isRotate) && (isSelected))
                   t = new AffineTransform();
                      t.setToRotation ((Math.toRadians (90)),(left+width/2) , (top+height/2) );
                      g2.transform(t);
                      g2.setColor(color);
                   g2.fill(wall);
                   g2.setColor(Color.red);
                    g2.draw(border);
                    g2.setTransform( origTransform );
                    return;
            else
                 g2.setColor(color);
              g2.fill(wall);
            if ((isSelected)&& !(isRotate))
                         g2.setColor(Color.red);
                         g2.draw(border);
                              else
                                   g2.setColor(Color.black);
                                   g2.draw(wall);
    }

  • Repainting picture on a canvas

    hey,
    Now I have the canvasses ready on my applet I would like to make it able to change the pictures when a button gets pressed.
    For a start I kept it really simple, but when I call the method which repaints the canvas it just won't work.
    This is what I have:
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.SystemColor;
    import java.awt.Toolkit;
    import java.awt.font.FontRenderContext;
    import java.awt.font.TextLayout;
    public class ImageCanvas extends Canvas {
    protected int width = 25;
    protected int height = 69;
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image img = toolkit.getImage("red3.gif");
    Image imgGreen;
    private double currentAngle;
    private Dimension size;
    public ImageCanvas() {
            setSize(width, height);
    public void paint(Graphics g)
        g.drawImage(img, 0, 0, width, height, this);
           public void setGreen()
                //Toolkit toolkit = Toolkit.getDefaultToolkit();
                img = toolkit.getImage("green3.gif");
                repaint();
           public void setAmber()
                //Toolkit toolkit = Toolkit.getDefaultToolkit();
                img = toolkit.getImage("amber3.gif");
                repaint();
    public Image getImage()
         return img;
    }Now the class from which the applet is run:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import java.awt.Graphics;
    public class TLCS extends Applet {
         Image image;
         ImageCanvas canvas1;
         Button button1;
         ImageCanvas canvas2;
         Button button2;
         ImageCanvas canvas3;
         ImageCanvas canvas4;
         ImageCanvas canvas5;
         ImageCanvas canvas6;
         ImageCanvas canvas7;
         ImageCanvas canvas8;
         ImageCanvas canvas9;
         ImageCanvas canvas10;
         ImageCanvas canvas11;
         ImageCanvas canvas12;
         Graphics g;
         Thread mythread;
         public void init()
          setSize(774,536);
          Toolkit toolkit = Toolkit.getDefaultToolkit();
          image = toolkit.getImage("Crossing.gif");
          canvas1 = new ImageCanvas();
          canvas2 = new ImageCanvas();
          canvas3 = new ImageCanvas();
          canvas4 = new ImageCanvas();
          canvas5 = new ImageCanvas();
          canvas6 = new ImageCanvas();
          canvas7 = new ImageCanvas();
          canvas8 = new ImageCanvas();
          canvas9 = new ImageCanvas();
          canvas10 = new ImageCanvas();
          canvas11 = new ImageCanvas();
          canvas12 = new ImageCanvas();
          //canvas1.paint(g);
          setLayout(null);
          //canvas1.setBounds(50, 80, canvas1.getWidth(), canvas1.getHeight());
          canvas1.setLocation(360, 430);
          button1 = new Button("1");
          button1.setBounds(360, 500, 20, 20);
          add(button1);
          canvas2.setLocation(400, 430);
          button1 = new Button("Light 2");
          canvas3.setLocation(440, 430);
          canvas4.setLocation(550, 260);
          canvas5.setLocation(590, 220);
          canvas6.setLocation(550, 180);
          //Graphics2D g2 = createGraphics2D(39, 99);
          //canvas4.drawDemo(39, 99, g2);
          canvas7.setLocation(320, 90);
          canvas8.setLocation(280, 90);
          canvas9.setLocation(240, 90);
          canvas10.setLocation(200, 300);
          canvas11.setLocation(170, 340);
          canvas12.setLocation(200, 380);
          add(canvas1);
          add(canvas2);
          add(canvas3);
          //add(canvas4);
          canvas3.setGreen();
          add(canvas4);
          add(canvas5);
          add(canvas6);
          add(canvas7);
          canvas7.setAmber();
          add(canvas8);
          add(canvas9);
          add(canvas10);
          add(canvas11);
          add(canvas12);
          //canvas1.setGreen();
          ActionListener al = new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                                  //Object s = e.getSource();
              //if (s == button1)
              canvas1.setGreen();
          button1.addActionListener(al);
         public void paint(Graphics g)
              g.drawImage(image, 0, 0, this);
    }I know I should use arrays but this is just in the beginning stages of the project.
    Now, in the init() method of TLCS class the canvas3.setGreen(); call works, cuz when I start the applet the right picture is shown.
    Now I'm wondering why it won't work on a button press.
    What did I do wrong?
    Thank you,
    Andre

    //  <applet code="TLCSAgain" width="100" height="100"></applet>
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class TLCSAgain extends Applet {
         Image image;
         Button button1;
         Button button2;
         ImageCanvas2 canvas1;
         ImageCanvas2 canvas2;
         ImageCanvas2 canvas3;
         ImageCanvas2 canvas4;
         ImageCanvas2 canvas5;
         ImageCanvas2 canvas6;
         ImageCanvas2 canvas7;
         ImageCanvas2 canvas8;
         ImageCanvas2 canvas9;
         ImageCanvas2 canvas10;
         ImageCanvas2 canvas11;
         ImageCanvas2 canvas12;
         public void init() {
               setSize(774,536);
               Toolkit toolkit = Toolkit.getDefaultToolkit();
               image = toolkit.getImage("images/Bird.gif");
               canvas1 = new ImageCanvas2();
               canvas2 = new ImageCanvas2();
               canvas3 = new ImageCanvas2();
               canvas4 = new ImageCanvas2();
               canvas5 = new ImageCanvas2();
               canvas6 = new ImageCanvas2();
               canvas7 = new ImageCanvas2();
               canvas8 = new ImageCanvas2();
               canvas9 = new ImageCanvas2();
               canvas10 = new ImageCanvas2();
               canvas11 = new ImageCanvas2();
               canvas12 = new ImageCanvas2();
               setLayout(null);
               button1 = new Button("1");
               button1.setBounds(360, 500, 20, 20);
               add(button1);
    //           button1 = new Button("Light 2");
               canvas1.setLocation(360, 430);
               canvas2.setLocation(400, 430);
               canvas3.setLocation(440, 430);
               canvas4.setLocation(550, 260);
               canvas5.setLocation(590, 220);
               canvas6.setLocation(550, 180);
               canvas7.setLocation(320, 90);
               canvas8.setLocation(280, 90);
               canvas9.setLocation(240, 90);
               canvas10.setLocation(200, 300);
               canvas11.setLocation(170, 340);
               canvas12.setLocation(200, 380);
               add(canvas1);
               add(canvas2);
               add(canvas3);
               add(canvas4);
               add(canvas5);
               add(canvas6);
               add(canvas7);
               add(canvas8);
               add(canvas9);
               add(canvas10);
               add(canvas11);
               add(canvas12);
               ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        Object s = e.getSource();
                        if (s == button1)
                            canvas1.setGreen();
               button1.addActionListener(al);
         public void paint(Graphics g)
              g.drawImage(image, 0, 0, this);
    class ImageCanvas2 extends Canvas {
        protected int width = 25;
        protected int height = 69;
        Image red;
        Image green;
        Image amber;
        Image img;
        private double currentAngle;
        private Dimension size;
        public ImageCanvas2() {
            setSize(width, height);
            makeImages();
            img = red;
        public void paint(Graphics g) {    
            g.drawImage(img, 0, 0, this);
        public void setGreen() {
            img = green;
            repaint();
        public void setAmber() {
            img = amber;
            repaint();
        public Image getImage(){
            return img;
        private void makeImages() {
            red = makeImage(Color.red);
            green = makeImage(Color.green.darker());
            amber = makeImage(Color.orange);
        private BufferedImage makeImage(Color color) {
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(width, height, type);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(color);
            g2.fillRect(0,0,width,height);
            g2.dispose();
            return image;
    }

  • ScrollPane Canvas repaint

    hello everybody,
    I am adding a Canvas to a ScrollPane and adding different Strings to this Canvas using drawString method.
    But the problem is that when i scroll up or sidewards then the contens are repainted and i can see the contents of the Canvas. How to do this.
    Pls help me out.
    I am putting down my code below.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.applet.*;
    public class MyTest extends Applet
    MyScroll sc;
    MyNewComponent newComponent;
    public void init()
    sc = new MyScroll();
    newComponent = new MyNewComponent();
    newComponent.setBounds(0,0,100,100);
    newComponent.addElements();
    sc.add(newComponent);
              sc.updateComponent(newComponent);
    add(sc);
              sc.validate();
    class MyNewComponent extends Canvas
    Vector lines,fonts,colors;
    int x=0,y=10;
    Enumeration linesEnu,colorEnu;
    public void MyComponent()
    public void addElements()
    lines = new Vector();
              fonts = new Vector();
    colors = new Vector();
    lines.addElement(" Jogi ");
    lines.addElement(" Prabha ");
    lines.addElement(" Kothi ");
    lines.addElement(" Naresh ");
              lines.addElement(" Murthy");
              lines.addElement(" vishal ");
    linesEnu = lines.elements();
                   colorEnu = colors.elements();
    public void paint(Graphics g)
    Font f = new Font("SansSerif",Font.BOLD,10);
    while(linesEnu.hasMoreElements())
    g.setColor(Color.black);
    g.setFont(f);
    g.drawString(""+linesEnu.nextElement(),x,y );
    y=y+10;
    public void update(Graphics g)
              paint(g);
    class MyScroll extends ScrollPane
         public void MyScroll()
         public void paint(Graphics g)
         public void update(Graphics g)
         public void updateComponent(MyNewComponent o)
              o.repaint();
    Thanks in advance

    In addition to the previous reply:
    You use an enumeration to go through the strings, which you create outside the paint method. As an enumeration only allows you to go through its contents once, the first call to paint after adding a string will work ok, whereas all subsequent calls will find an empty enumeration, i.e. one, where hasMoreElements returns false immediately.
    So, move your inesEnu = lines.elements() command to the paint-method, too.
    Bye, Marc.

  • Is it possible to append a string on canvas without calling repaint() ??

    Hi..experts
    I am new to J2ME programming. i want to append characters on canvas one by one.
    is it possible to append a string to another that is allready drawn without repainting all canvas.
    please help me.
    Thanks a lot

    without repainting all canvas.if your not comfortable repainting the entire canvas, You can use the selective repaint function. it repaints only the area specified by you
    repaint(int x, int y, int width, int height)
    //Requests a repaint for the specified region(x,y) of the Canvas.ps: selective repainting is the VM's decision

  • 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();
      }

  • Repaint a canvas

    Hi everybody,
    I have to implement a frame in which you can draw some lines. Those lines are the edges of cells for a mobile network.
    But when I drew a line, it disappeared immediately. How can I resolve this ?
    The schematic is heavy to load, so I want to save it in a "virtual canvas", to make it easy to repaint the canvas. I don't know how do that.
    Here is my code for the frame :
    public class FAPShowMap extends Canvas implements MouseListener {
         private Graphics gr ;
         private Frame frame ;
         public FAPShowMap(Vector ed) {
              super() ;
              frame = new Frame("Carte des cellules et antennes") ;
              frame.setSize(600,600) ;
              frame.setResizable(false) ;
              frame.addWindowListener(new GenericWindowListener()) ;
              frame.add(this) ;
              frame.pack() ;
              this.addMouseListener(this) ;
              frame.setVisible(true) ;
              this.addNotify() ;
              paint(new Vector()) ;
         public void paint(Vector ed) {
              gr = this.getGraphics() ;
              gr.drawLine(3,3,200,200) ;
              this.paint(gr) ;
         public void mouseClicked(MouseEvent e) {
              this.repaint() ;
              gr.drawLine(50,50,600,100) ;
              this.paint(gr) ;
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public static void main(String[] args) {
              new FAPShowMap(null) ;
    I will be very glad if you can help me
    Thank you
    Agni

    Hi Agni,
    Reread my previous post. In particular, it mentions the probable cause of your problem. Note that it's not caused by overloading the paint method; it's what you're doing inside the overloaded method.
    Changing your overloaded paint method to be:public void paint(Vector ed)
       gr = this.getGraphics() ;
       gr.setColor(java.awt.Color.black);
       gr.drawLine(3,3,200,200) ;
    }should work, but with a problem. Namely, when the component repaints itself, the line will be erased. Take a look at the tutorials for the explanation of why this happens and how to correct for it.
    I strongly recommend seeking a definitive source for Java programming if you are just starting. The "Core" series from Sun MicroSystems Press is very good. Jumping in (especially with graphics) may cause more aggrevation than progress.
    Regards,
    Nick

  • Netbeans 6.1m canvas repaint

    Hi there.
    Don't know why but have no luck with repaint.
    i have
    layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addComponent(canvas, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)and try to paint an image on this canvas. this.width = w;
            this.height = h;
            this.pixels = new int[pxs.length];
            for (int ii = 0; ii < pxs.length; ii++) {
                this.pixels[ii] = pxs[ii];
            this.updateImg();
        private void updateImg() {
            img = createImage(new MemoryImageSource(width, height, this.pixels, 0, width));However no luck with it
    Maybe you have a simple example?
    (full code is here mif.vu.lt/~sasa3871/Stone.zip
    Maybe someone else has some kind of an example where a user can just give coordinates where to paint things.
    In my case i need to have the posibility to read information by pixels.
    Edited by: isolated on Oct 6, 2008 10:29 AM
    Edited by: isolated on Oct 6, 2008 11:29 AM

    The code is provided here too:
    [http://pastebin.com/m5b9b16fa] - program part that extends canvas and generates image
    [http://pastebin.com/m203b0295] - part where we should load image.
    As i mentioned before this problem can be caused by the netbeans, so if anybody uses netbeans try the whole project,
    it will be more informative.
    Edited by: isolated on Oct 6, 2008 10:34 PM

  • J2ME - Canvas - repaint

    Hi,
    I have a stupid question. As far as I know the Canvas class of J2ME doesn't have getGraphics() method. That means, that I can't get the graphic representation of the Canvas object and so I can't make changes calling the properly methods of the Graphics class.
    However, the repaint() method is the only way, to do this?
    Say, I want to draw a string to the screen when the user hits a button.
    How can I do this?
    Thanks in advance,
    holex

    Hi!! I�ve a little problem, when i used repaint() method, the canvas don�t clear.
    int k=0;
    protected void pointerPressed( int x, int y){
    if (((x>0) && (x<5)) && ((y>0)&& (y<5))){
    k=1;
    repaint();
    protected void paint(Graphics g) {
    if (k==0) {
    g.drawRect(0,0,5,5);
    if (k==1) {
    g.drawRect(1,10,10,10);
    For example, when k=0 the canvas draw a rectangle, and when k=1 the canvas draw another rectangle, but i want to erase first rectangle and it�s not occur when i used repaint() method. Please, what i need to do ?

  • Canvas repainting in web migration

    HI,
    We are attempting to migrate our forms to the web. In several cases, we experience intermittent screen re-paints. I have made sure that we have Visible=NO and Raise on entry = yes specified for all but the first canvas. (All of these forms have multiple canvases - some as many as 20 canvases per form!)
    In one particular case, I press a button to launch a LOV, then press a button to close the LOV. Sometimes the repaints happen before the LOV is displayed, other times, the repaints occur after closing.
    This is a frustrating issue - if it was consistent, it would be much easier to fix!
    Any ideas?
    tia,
    r.b.

    A number of flicker issues have been addressed in forms patchsets. Worth noting that some JVMs exhibit flickering problems more than others. These problems can often be
    difficult to reproduce so it would be helpful to know what version of forms and the JVM you are using. If you find that it works in one patchset but not another that would also be useful to know. Ultimately you need to log a testcase with support so that the problem can be investigated.
    I know that we are already investigating some (at least on the surface) issues which sound similar.
    Regards
    Grant Ronald
    Forms Product Managemen

  • Repainting a custom canvas

    I have sub-classed java.awt.Canvas to make my own Progress Bar looking component.
    Then I place that in a java.awt.Dialog, when the user clicks the java.awt.Button, the progress bar should repaint() itself to fill the bar up to the point of it's progress all of which is done by calling a custom method that moves the progress value by 1 and calls repaint() inside a for-loop.
    It works fine except for it does not repaint until the for-loop is done, but I do call inside the loop the canvas' repaint() method, as well as the custom progress() method which itself calls repaint().
    I have a loop that makes two (2) calls to method repaint() of class Canvas, but the Canvas does not repaint() until the end of the loop.

    placing repaint inside a for loop will NOT do what you want it to.
    I will have to go into a little more depth to explain why....
    when repaint is called, it does not cause an immediate repaint - instead - it posts a repaint request in the event queue. The event queue will not be serviced until your for loop has completed, so none of the repaints will be performed until the end of the loop.
    What you need to do, is create a seperate Thread, that calls repaint, and then sleeps for a set period (something like 100ms) while your updating thread is sleeping, the repaint event you have requested(by calling repaint()) will be processed, and you will see the progressbar update.
    rob,
    p.s.
    another, slightly less important problem is that multiple identical paint events in the event queue will be coalesced (merged) into a single repaint. For normal operation this is a desirable feature however, if you ever write a game in java, you will discover this may cause problems.

  • Problem about canvas repaint!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    class DrawPie extends Canvas{
    Container cont;
    public DrawPie(Container parent){
    cont=parent;
    public void addinContainer(){
    this.setSize(200,200);
    cont.add(this,BorderLayout.SOUTH);
    public void paint(Graphics g){
    g.drawString("This is test",20,20);
    public class WelFrame extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();
    // Construct the frame
    public WelFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    // Component initialization
    private void jbInit() throws Exception {
    Button btn=new Button("Open");
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    btn.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    btn_actionPerformed(e);
    contentPane.add(btn,BorderLayout.NORTH);
    this.setTitle("Welcome to JBuilder");
    this.setSize(new Dimension(400, 300));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    //File | Exit action performed
    public void jMenuFileExit_actionPerformed(ActionEvent e) {
    System.exit(0);
    void btn_actionPerformed(ActionEvent e) {
    DrawPie dp=new DrawPie(contentPane);
    dp.addinContainer();
    public static void main(String[] args){
    WelFrame wf=new WelFrame();
    wf.show();
    I can't get the text painted when click the button open.But when i resize the Frame,the text appeared.
    how can i get the text painted when i click the button open.Thanks a lot.

    When you add a component to another component, call it the parent component, AFTER YOU HAVE CONSTRUCTED THE PARENT COMPONENT, you need to call the method validate()on the parent component to insure that this component, the parent component, has a valid layout. In your code, you're adding your component which extends Canvas to the parent component which extends JFrame AFTER instanciating it. Hence, you need to call validate() on this parent right after adding the child component. In other words, your method btn_actionPerformed should look like the following:
    void btn_actionPerformed(ActionEvent e) {
    DrawPie dp=new DrawPie(contentPane);
    dp.addinContainer();
    validate(); //or this.validate();
    calling validate() will insure re-arrenging all children correctly according to the parent layout. When you resize your form, validate is called automatically and that's why the child component shows up.
    Without calling validate(), your newly added child component is not resized and located according to the parent layout. it's probably with the size 0,0 and that's why you're not seeing the text.
    I hope I explained it clearly enough

  • Repainting specific areas of the canvas

    Hello, ive been trying all day to search for good examples on how to repaint specific areas of the screen. I know there are som atributes to the repaint() method, but im trying to repaint an area of 20x20 px on the left corner of the screen with a thread. Can someone pleeeeeeez guide me maybe to how to accomplish this. Thanks in advance.

    Well you would call repaint(0,0,20,20), instead of just repaint().
    But more importantly is that you set up your paint() method so that it can recognize that you're only repainting part of the screen. Something like:
    public void paint(Graphics g) {
      // you use the Graphics.getClip????() methods to find out the clipping region for this paint request:
      int clipX = g.getClipX();
      int clipY = g.getClipY();
      int clipW = g.getClipWidth();
      int clipH = g.getClipHeight();
      // now, if you called repaint(0,0,20,20) then clipX=0, clipY=0, clipW=20 and clipH=20
      // so you can now use these variables to set up code that only repaints the appropiate part of the screen
    }Even if you don't set up the paint() method this way, it will still work, because anything you paint outside the clipping region won't show up on screen. But I imagine that you want to repaint just part of the screen because you need the painting to be faster, so unless you take the clipping region into account, all the paint code will be executed and you won't gain too much speed by only repainting part of the screen.
    shmoove

Maybe you are looking for

  • How do I find the unused iMovie files so I can delete them?

    I'm using a MacBook, late 2008, running Lion & iMovie '11. 164 GB hard drive, 4 GB RAM. I imported a long movie (well, an hour & a half) into iMovie - at least, I TRIED to. It quit about 3/4 of the way through the import. I tried importing again, the

  • Photoshop CS5 crashes whenever I try to save a file

    Recently, my graphics card stopped working, so I've been forced to use an onboard GPU until I can get the money to buy a new one. The problem though, is that the onboard GPU is VERY old (approximately 6 or so years), and every time I try to save some

  • Why is the ipad mini without whatsapp ??

    I Need whatsapp on my ipad mini but in the store there is no whatsapp messenger for ipad i searched internet but i dont want to install jailbreak and i dont have an iphone ? Apple should let whatsapp downloaded on ipads !!

  • CTI Connector project SAP Cloud for Customer

    Hello Experts, I am searching for the CTI Connector project used for enabling outbound calls as it is described in the SAP Cloud for Customer CTI Guide: "Download the CTI Connector project from the SAP Service Marketplace and install it." Unfortunate

  • Transfering photos from different pcs without deleting existing photos

    How can i copy photos to ipad if i use different pcs in every 2 weeks, without losing the existing photos?i think itunes will delete them. I am traveling and dont have a home computer.thanks