ConcurrentModificationException in drawing code

Hi all,
I'm getting a ConcurrentModificationException and I'm having a bit of a hard time figuring out how to prevent it - I can't even really understand why it happens yet.
I'm running a simulation of moving bodies in some world, and am using a Swing Timer to fire drawing events. The events fired by the timer are handled by a class WorldView, which draws the world and in turn uses BodyView objects to draw the bodies in the world. The exception occurs in the following code:
public class SimAgentBodyView extends AgentBodyView {
  @Override
  public void draw( Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.red);
    //cam is a simulated camera object mounted on the agent body               
    List<ISimBody> visBodies = cam.getVisibleObjects();
    for ( Body b : visBodies ) //Exception occurs in this loop
     g2d.draw(b.getFigure().getBounds2D());So apparently the visBodies list is being modified somewhere else while the drawing occurs. I don't really get this since I only use a single thread for the simulation which executes in the even-dispatching thread. The Timer runs in a separate thread but according to the API the event handler for the timer executes in the event-dispatching thread; i.e. both the simulation and the drawing mechanism are executing in the event-dispatching thread, so how can the simulation modify the list while the drawing happens?
I'm rather short on time and the drawing is usually switched off to speed up the simulation anwyay, so even if it is not obvious what the problem is, is there a quick way to fix this? E.g. adding a synchronized block to the drawing code?
Thanks
Matt

jverd wrote:
CME is thrown on a best effort basis. There's no guarantee when it will be thrown, or even that it will be at all.I understand, thanks.
Before you avoid the clear and simple solution for performance reasons, have you actually tested and found a performance problem with it?Good point, I haven't. But from profiling the app I know that during a standard run the list will be modified around 400 million times, and read (a loop through the entire list) about 200k - 800k times, depending on how long the run takes. From what I've read it seems that a concurrent collection will take significantly longer in this case. But you're right, maybe I should just try.
I only posted a tiny bit of the code because at the time I did think that was the relevant bit, since I was under the impression that there was just a single thread accessing the list. The complete code follows, although again I'll take out parts that do not involve the list to make it clearer.
public class LineCamera implements PhysicalSensor {
     public List<ISimBody> getVisibleObjects() {
          return visibleObjects;
     @Override
     public double[] getReading() {
          List<Body> objectsInRange = world.getIntersectingObjects(visionArea);
          visibleObjects.clear(); //<--- List is cleared here
          calcImage(objectsInRange);
          return image;
        public void calcImage( List<Body> objects ) {
          Set<BodyDistance> sortedObjs = sortObjectsByDistance(objects);
          for ( Path2D.Double slice : slices ) {
               for ( BodyDistance obj : sortedObjs ) {
                    if ( slice.intersects(obj.bounds) ) {
                         visibleObjects.add(obj.body); //<--- List is modified here
                                        ...The code that reads the list is just the code that I posted earlier. The quick and dirty solution that I adopted now is just to clone the list in the code that does the drawing. Since the drawing is mainly for testing and seeing what's going on, speed is not so important there. Plus this avoids having to synchronize the modifications on the list; since this code is always executed (even when drawing is switched off), speed is of the essence. However it's quite nasty of course so if you know of anything better please let me know. Thanks!

Similar Messages

  • Subsitute drawImage by nativa drawing code

    Hi,
    I'm not quite sure this is the right forum to post my question. It's been a while since I visited these fora and there used to be a forum specifically for Java 2D topics, but I can't seem to find it. So I'll post it here and hope I guessed right.
    I was wondering about some drawing issue I had some time ago. I made an application using a custom, rather complex, backgroundimage and it started up pretty slow because it needed to load and draw the image. And I was wondering if it would be faster and more memory-efficient if in stead of using the drawImage()-method one used 'native' drawing code. You could make a program that reads an image and, using the provided array of data, puts together a sequence of drawing instructions like drawPoint with specified color or drawLine with the correct color so that the image generated from this block of code is exactly the same as the image from the resourcefile. And so my question is if this would be preferable to using the drawImage-method, if it would be faster and more memory-efficient (seeing that the code to do this would probably be a lot smaller than the actual imagefile and you also wouldn't need a load-buffer)?
    Thanks in advance,
    Sam

    Thanks for all your help so far.
    However, having changed gameLoop to:
        public void gameLoop() {
            long startTime = System.currentTimeMillis();
            long currTime = startTime;
            while (isRunning) {
                long elapsedTime = System.currentTimeMillis() - currTime;
                currTime += elapsedTime;
                update(elapsedTime);
                screen.repaint();
                screen.update();
        }and paintComponent to:
        public void paintComponent(Graphics g){
         game.draw(getGraphics());
        }I now get a NullPointerException which traces back to GameCore.draw then Screen.paintComponent, then JComponent.paint, etc. (it's a long one, and i don't know how to copy it here from the command prompt). Why's that happening?
    Thanks
    Edit: you can actually continue playing after the nullpointerexception has reared its head - it doesn't affect anything, but the screen is now ALL flickering, whereas in the original problem the background image was fine, but the images that made up the tiles in the map were flickering. Now, everything in the JFrame flickers.
    Edited by: Pulkse.co.uk on Jun 19, 2009 2:58 AM

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Which is better for drawing JPGs on JLabel: ImageIcon or directly?

    I'm currently using this everywhere.
    BufferedImage bi;
    Jlabel jLabel;
    ImageIcon img = new ImageIcon( bi );
    jLabel.setIcon(imgIcon);but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
    (from a subclass of JLabel)
    public void paintComponent( Graphics g ) {
      super.paintComponent( g );
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );Is this more efficient or better form? Should I update my code everywhere?
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
    public void mouseEntered(MouseEvent e) {
      Graphics g = this.getGraphics();
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );
    }what's wrong?

    Is this more efficient or better form?
    No.
    Should I update my code everywhere?
    It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
    Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
    stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
    Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
    Is there a good place to go to get a better understanding of this, or just ask on this forum?
    Ask when you need help.
    Resources that may be helpful to get started:
    Lesson: Writing Event Listeners
    Lesson: Performing Custom Painting
    How to Use Icons
    Lesson: Working with Images
    Core Java Technologies Tech Tips.

  • Drawing a special cursor: completely repaint everytime or only a region?

    Hello, I'm currently building an application which displays a BufferedImage. When I move the cursor in the the component that displays the BufferedImage my app draws a special cursor. It's a square which is moved only if my current position is dividable by 16 (if there was a grid, it would change it's position when the mouse moves to another square in the grid, it is around the square that the mouse occupies). At first, I was only using on thread so the application was a little laggy and my cursor thing didn't work too well. So I decided to use another thread to take care of my cursor. The drawing is in another class (external to the drawing class), therefore, I use getGraphics (since my drawing class subclasses JComponent). I signal a draw by changing a variable. I have to erase my old cursor to draw the new one. The problem is that my component "'flashes" gray instead of staying the way it should be (which is black, for now). Here are my questions: Why does it flash gray ? and what should I do to change that?
    Here's my code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    class Cursor implements Runnable {
         public boolean draw;
         public int[] iCursorCoord;
         public JComponent drawSurface;
         private Thread t;
         private Rectangle cursor;
         Cursor(){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(int[] initCoord){
              cursor = new Rectangle(initCoord[0],initCoord[1],15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = null;
         Cursor(JComponent drawSurf){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, int[] initCoord){
              cursor = new Rectangle(initCoord[0], initCoord[1], 15, 15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = initCoord[0];
              iCursorCoord[1] = initCoord[1];
              draw = false;
              drawSurface = drawSurf;
         public void init(){
              t.start();
         public void run(){
              while(true){
                   if(!draw) continue;
                   draw = false;
                   cursor.x = iCursorCoord[0];
                   cursor.y = iCursorCoord[1];
                   System.out.println("Inside Cursor::run()");
                   Graphics2D gfx = (Graphics2D) drawSurface.getGraphics();
                   this.completePaint(gfx);
                   Color current = gfx.getColor();
                   gfx.setColor(new Color(84,255,3));
                   gfx.draw(cursor);
                   gfx.setColor(current);
         private void completePaint(Graphics2D gfx){
              int layer = MapMaker.getLayerMode();
              if(layer != 4){
                   BufferedImage bi = MapMaker.getCurrentMap().getData(MapMaker.getLayerMode());
                   gfx.setPaint(new TexturePaint(bi, new Rectangle(0,0,MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16)));
                   gfx.fillRect(0, 0, MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16);
                   //gfx.drawImage(bi, null, 0,0);     
              } else {//Will be implemented later, render will be modified
                   System.out.println("Will be implemented later");
    }P.S.: This is only part of my code. There are other classes that I do not post because I believe it is not necessary. I will post the full code if needed.

    You need to override the paint(Graphics g) method. E.g.:
    public class MyPanel extends JPanel {
         public void paint(Graphics g) {
                   super.paint(g);
                    // ... do draw code here
    }The reason your app is flashing is because your code only executes
    when the thread is requests it to. Inbetween the time your code is
    executing, other threads are calling the paint(Graphics g) method.
    Gray is the default color used in painting.
    You can use a thread to call the repaint() method, but no drawing
    should be done in the thread.

  • Draw line using  Acrobat SDK

    I want to draw line on pdf page. I have x,y coordinate depend upon that i want to draw line on page. please reply
    Thanks in advance

    Thanks Leonard..
    This is my Circle draw code.. but it's not working properly..
    moveto() and CurveTo() are mwthod it is defined like Draw Curve. please give me some suggestion about it..
    ASFixed inCenterX = mediaBox.left;
    ASFixed inCenterY = mediaBox.top;
    ASFixed inRadius = ASInt32ToFixed(2);
    PDEPath mov = MoveTo( inCenterX + inRadius, inCenterY );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)mov);
    PDEPath rect1 = CurveTo( inCenterX + inRadius, inCenterY + inRadius * ARC_MAGIC, inCenterX + inRadius*ARC_MAGIC, inCenterY + inRadius,
    inCenterX, inCenterY + inRadius );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)rect1);
    PDEPath rect2 = CurveTo( inCenterX - inRadius*ARC_MAGIC, inCenterY + inRadius, inCenterX - inRadius, inCenterY + inRadius*ARC_MAGIC,inCenterX - inRadius, inCenterY );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)rect2);
    PDEPath rect3 = CurveTo( inCenterX - inRadius, inCenterY - inRadius*ARC_MAGIC, inCenterX - inRadius*ARC_MAGIC, inCenterY - inRadius,inCenterX, inCenterY - inRadius );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)rect3);
    PDEPath rect4 = CurveTo( inCenterX + inRadius*ARC_MAGIC, inCenterY - inRadius, inCenterX + inRadius, inCenterY - inRadius*ARC_MAGIC,
    inCenterX + inRadius, inCenterY );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)rect4);
    PDEPath close = CloseTo(inCenterX + inRadius, inCenterY );
    PDEContentAddElem(pdeContent, kPDEAfterLast, (PDEElement)close);
    HOw to draw circle using Acrobat SDK?
    Thanks in advance..

  • Flash Player 11 will also mean enhanced Vector Drawing & Gradient performance?

    I'm wondering if in order to benefit of the GPUs power we will be forced to use Stage3D.
    Will old games also feel better in Flash Player 11? Does Flash Player 11 accelerate old 2D drawing code by passing traditional gradient & vector calculations to the GPU?

    Ouch. Sorry, thanks for the tip! There are so many Forums (but they are well categorized) I kinda missed that one ::- D.
    Done!
    http://forums.adobe.com/thread/905556

  • Drawing on top of an image

    Hello!
    I am trying to create a Panel on which I can draw stuff using the mouse. I have managed to get it working, apart from one small part. I want to have an image (jpg) as a background, and as soon as I try to add an image either the image does not show or the drawing stuff stops working.
    Here is my working drawing code (i.e. without image):
    public void paintComponent(Graphics g) {
             super.paintComponent(g);
             if (image == null || image.getWidth(null) != getWidth()
                   || image.getHeight(null) != getHeight()) {
                image = (BufferedImage) createImage(getWidth(), getHeight());
                graph = (Graphics2D) image.getGraphics();
                graph.fillRect(0, 0, getWidth(), getHeight());
                graph.setColor( Color.white );
                graph.setStroke(new BasicStroke(3));
                graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON));
             Rectangle r = g.getClipBounds();
             g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
                   r.x + r.width, r.y + r.height, null);
             if (endPoint != null) {
                g.setColor(currentColor);
                if (shapeType == 0)
                   g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   g.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   g.drawRect(pn.x, pn.y, pn.width, pn.height);
             public void mouseDragged( MouseEvent m ) {
                if (shapeType > 3 && shapeType != 8)
                   return;
                if (endPoint == null)
                   endPoint = new Point();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
                pn.x = Math.min(startPoint.x, m.getX());
                pn.y = Math.min(startPoint.y, m.getY());
                pn.width = Math.abs(m.getX() - startPoint.x);
                pn.height = Math.abs(m.getY() - startPoint.y);
                if (shapeType == 0) {
                   endPoint.setLocation(m.getPoint().getLocation());
                if (shapeType == 3) {
                   graph.setColor(currentColor);
                   graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
                   startPoint = m.getPoint();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseReleased(MouseEvent m) {
                if (endPoint != null)
                   draw();
                endPoint = null;
             public void mousePressed(MouseEvent m) {
                startPoint = m.getPoint();
             public void draw() {
                graph.setColor(currentColor);
                if (shapeType == 0)
                   graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   graph.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   graph.draw(pn);
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             }To me it seemed logical to add:
    graph.drawImage(my_gif, 0, 0, this);at the end of the if statement, but that did not work.
    Where and how should I add the image?
    Thanks!

    Thanks for answering!
    Here is the entire code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.JApplet;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    @SuppressWarnings("serial")
    public class ImageExample extends JApplet {
       private static final Dimension DRAWING_AREA_SIZE = new Dimension(300,300);
       private static final Point DRAWING_AREA_UPPER_LEFT = new Point(100,50);
       private static final Color BACKGROUND_COLOR = Color.black;
       private Image my_gif;
       private Color currentColor = Color.white;
       private JLabel currentColorIndicator;
       private JPanel pane = new JPanel(null);
       Point startPoint, endPoint;
       Rectangle pn = new Rectangle();
       BufferedImage image;
       Graphics2D graph;
       int shapeType = 3;
       public void init() {
          setContentPane(pane);
          my_gif = getImage( getDocumentBase(), "fractal.gif" );
          pane.setOpaque(true);
          pane.setBackground(BACKGROUND_COLOR);
          createColorMap();
          DrawingPanel drawingPanel = new DrawingPanel();
          drawingPanel.setBounds(DRAWING_AREA_UPPER_LEFT.x, DRAWING_AREA_UPPER_LEFT.y, DRAWING_AREA_SIZE.width,
                DRAWING_AREA_SIZE.height);
          pane.add(drawingPanel);
       // Private methods
       private void createColorMap() {
          ColorPickerListener listener = new ColorPickerListener();
          JLabel colorText = new JLabel("Color");
          colorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y-20, 50, 25);
          colorText.setForeground(Color.white);
          pane.add(colorText);
          JLabel redColor = new JLabel("");
          redColor.addMouseListener(listener);
          redColor.setBackground(Color.RED);
          redColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+10, 50, 30);
          redColor.setOpaque(true);
          pane.add(redColor);
          JLabel blueColor = new JLabel("");
          blueColor.addMouseListener(listener);
          blueColor.setBackground(Color.blue);
          blueColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+40, 50, 30);
          blueColor.setOpaque(true);
          pane.add(blueColor);
          JLabel whiteColor = new JLabel("");
          whiteColor.addMouseListener(listener);
          whiteColor.setBackground(Color.white);
          whiteColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+70, 50, 30);
          whiteColor.setOpaque(true);
          pane.add(whiteColor);
          JLabel greenColor = new JLabel("");
          greenColor.addMouseListener(listener);
          greenColor.setBackground(Color.green);
          greenColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+100, 50, 30);
          greenColor.setOpaque(true);
          pane.add(greenColor);
          JLabel blackColor = new JLabel("");
          blackColor.addMouseListener(listener);
          blackColor.setBackground(Color.black);
          blackColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+130, 50, 30);
          blackColor.setOpaque(true);
          pane.add(blackColor);
          JLabel grayColor = new JLabel("");
          grayColor.addMouseListener(listener);
          grayColor.setBackground(Color.gray);
          grayColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+160, 50, 30);
          grayColor.setOpaque(true);
          pane.add(grayColor);
          JLabel yellowColor = new JLabel("");
          yellowColor.addMouseListener(listener);
          yellowColor.setBackground(Color.yellow);
          yellowColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+190, 50, 30);
          yellowColor.setOpaque(true);
          pane.add(yellowColor);
          // Display currently chosen color
          JLabel currentColorText = new JLabel("Current");
          currentColorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+230, 50, 25);
          currentColorText.setForeground(Color.white);
          pane.add(currentColorText);
          currentColorIndicator = new JLabel("");
          currentColorIndicator.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+260, 50, 30);
          updateCurrentColorLabel();
          currentColorIndicator.setOpaque(true);
          pane.add(currentColorIndicator);
       private void updateCurrentColorLabel() {
          currentColorIndicator.setBackground(currentColor);
          currentColorIndicator.setForeground(new Color(255 - currentColor.getRed(), 255 - currentColor.getGreen(),
                255 - currentColor.getBlue()));
       // Private classes
       private class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener {
          BufferedImage image;
          public DrawingPanel() {
             addMouseMotionListener(this);
             addMouseListener(this);
          public void paintComponent(Graphics g) {
             super.paintComponent(g);
             if (image == null || image.getWidth(null) != getWidth()
                   || image.getHeight(null) != getHeight()) {
                image = (BufferedImage) createImage(getWidth(), getHeight());
                graph = (Graphics2D) image.getGraphics();
                graph.fillRect(0, 0, getWidth(), getHeight());
                graph.setColor( Color.white );
                graph.setStroke(new BasicStroke(3));
                graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON));
                graph.drawImage(my_gif, 0, 0, this);
                System.out.println(my_gif + " <- my_gif");
                System.out.println(my_gif.getWidth(this) + " <- my_gif.getWidth(this)");
                System.out.println(my_gif.getHeight(this) + " <- my_gif.getheight(this)");
             Rectangle r = g.getClipBounds();
             g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
                   r.x + r.width, r.y + r.height, null);
             if (endPoint != null) {
                g.setColor(currentColor);
                if (shapeType == 0)
                   g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   g.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   g.drawRect(pn.x, pn.y, pn.width, pn.height);
             public void mouseDragged( MouseEvent m ) {
                if (shapeType > 3 && shapeType != 8)
                   return;
                if (endPoint == null)
                   endPoint = new Point();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
                pn.x = Math.min(startPoint.x, m.getX());
                pn.y = Math.min(startPoint.y, m.getY());
                pn.width = Math.abs(m.getX() - startPoint.x);
                pn.height = Math.abs(m.getY() - startPoint.y);
                if (shapeType == 0) {
                   endPoint.setLocation(m.getPoint().getLocation());
                if (shapeType == 3) {
                   graph.setColor(currentColor);
                   graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
                   startPoint = m.getPoint();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseReleased(MouseEvent m) {
                if (endPoint != null)
                   draw();
                endPoint = null;
             public void mousePressed(MouseEvent m) {
                startPoint = m.getPoint();
             public void draw() {
                graph.setColor(currentColor);
                if (shapeType == 0)
                   graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   graph.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   graph.draw(pn);
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseClicked(MouseEvent arg0) {}
             public void mouseEntered(MouseEvent arg0) {         }
             public void mouseExited(MouseEvent arg0) {         }
             public void mouseMoved(MouseEvent arg0) {         }
       //Listeners
       private class ColorPickerListener extends MouseAdapter {
          public void mouseClicked(MouseEvent e) {
             JLabel color = (JLabel) e.getSource();
             currentColor = color.getBackground();
             updateCurrentColorLabel();
    }So the problem might be that the system.outs in there put out:
    sun.awt.image.ToolkitImage@1a0c10f <- my_gif
    -1 <- my_gif.getWidth(this)
    -1 <- my_gif.getheight(this)I don't know how to fix so that the height and width are set. Isn't it enough to do the:
          my_gif = getImage( getDocumentBase(), "fractal.gif" );before initializing the drawing panel?
    Thanks again!

  • Sepearating Drawing and Updating to Abuse and others

    Well Abuse told me before that my sprite engine should not use passive rendering, instead it should use active rendering. I couldn't figure out what this meant until last night. I think he meant that I should separate my drawing code from my updating code. So right now everything is called from the same thread about 25 times a second. But how could I separate the render method into a separate thread so that it just draws as fast as possible? Also, what would the synchronization issues be? I'm guessing I would need to synchronize all my sprite variables.

    Thanks for the great link! I changed my game from using repaint() to using paint(Graphics g) and everything is much faster! I'm considering switching from BufferedImage to VolatileImage but I don't quite understand the contentsLost() part of it.
    But if I want even better performance I see I need a separate drawing loop from my updating loop, hence a different thread. That's what I was talking about before. I can't find this required method for that though in the Java API:
    getPaintGraphics()
    Also, I'm curious about the synchronization issues with that. What if the x coordinates of a sprite were just updated and y coordinates are not yet updated, or one sprite is updated before another. Then won't the drawing done be off? No such problems exist with a single thread that both updates and paints.

  • Drawing surface

    I have a small program, and right now it's just the interface. This one is suppose to plot polynomials, but my drawing surface isn't showing up. I'll post the code for the drawing surface, which is an external class, if needed, I will post the whole thing.
    import java.awt.image.*;
    import java.awt.*;
    import javax.swing.*;
    public class ImagePlotter extends JPanel
         BufferedImage cartisianImage;
         Graphics2D g2d;
         public ImagePlotter()
         public void paintComponent(Graphics g)
              g2d = (Graphics2D)g;
              int width = 300;
              int height = 300;
              cartisianImage = (BufferedImage)(this.createImage(width,height));
              Graphics2D gc = cartisianImage.createGraphics();
              g2d.drawImage(cartisianImage,null,0,0);
         public void drawPolynomialLine(int[] xPoints, int[] yPoints, int count)
              g2d.drawPolyline(xPoints,yPoints, count);
              repaintComponent();
         public void repaintComponent()
              repaint();
    }In the "driver" class, I do this:
    ImagePlotter ip = new ImagePlotter();
    //then i add it to the container
    pane.add(ip);

    Why use a buffered image? You can make that work, but it's generally easier and just as effective to do the drawing in your paintComponent() method.
    Try adding this to your ImagePlotter() constructor:
    setPreferredSize( new Dimension(300, 300) );Then your enclosing JFrame can just pack() and it should come out all right.
    In your paintComponent() method, discard the image and just call your draw method. But try something simple, to make sure the driver and drivee are working together. Something like this in paintComponent():
    g.setColor( Color.BLUE );
    g.fillRect( 10, 10, 100, 100 );When that works, get on to debugging the real draw code. And since you'll be calling the draw code from paintComponent(), discard repaintComponent() and the call to it in drawPolynumialLine().
    Good luck!

  • I have a graphics 2D object which takes ages to draw....

    I have made a graphics 2D object which draws rectangles of sizes (5,5) accross the width and height of the screen on at a time.
    As you can imagine, this takes ages!!!
    does any one have an idea of how to make this quicker without sacrificing the resolution???
    thanks!

    well, withought code I just can give you some tipps:
    * don't create a new Color in the loop, try to share it
    * try to paint rectangles with same color at one time -> minimize the time how often setColor is called
    * do not create new Objects (like Color) in your paint-loop, share share share...
    btw. I would cache it in an image, otherwise everytime the window-content is invalidated (which can happen quite frequently) your slow drawing code is called.
    btw2. I can't smell your mistakes over the net, already told you to show your rendeing code.

  • Code Review on a Full Screen Graphics Wrapper

    Hi all, if you could be so kind, could I get a quick review of my full screen graphics wrapper? It is giving strange flickering issues on an OSX TIBook, although that may be Apple's implementation. Also, am I breaking any major rules? Thanks, Ryan
    package rpgClient.graphics;
    import java.awt.*;
    import java.awt.image.*;
    public class Screen
         private Frame mainFrame;
         private GraphicsDevice gd;
         private BufferStrategy bs;
         private DisplayMode oldDisplayMode;
         private DisplayMode newDisplayMode;
         public Screen(GraphicsDevice gd, DisplayMode dm)
              System.setProperty( "sun.java2d.translaccel" ,"true" );
              this.gd = gd;
              oldDisplayMode = gd.getDisplayMode();
              newDisplayMode = dm;
              GraphicsConfiguration gc = gd.getDefaultConfiguration();
              mainFrame = new Frame(gc);
              mainFrame.setUndecorated(true);
              mainFrame.setIgnoreRepaint(true);
         //screen specifications
         public static GraphicsDevice[] getGrephicsDevices()
              return GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
         public static GraphicsDevice getDefaultGraphicsDevice()
              return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
         public static DisplayMode createDisplayMode(int width, int height, int bitdepth)
              return new DisplayMode(width, height, bitdepth, DisplayMode.REFRESH_RATE_UNKNOWN);
         public static DisplayMode[] getDefaultDisplayModes()
              return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayModes();
         public static DisplayMode[] getDisplayModes(GraphicsDevice gd)
              return gd.getDisplayModes();
         public static boolean isValidDisplayMode(GraphicsDevice gd, DisplayMode dm)
              DisplayMode[] dms = getDisplayModes(gd);
              for(int i = 0; i < dms.length; i++)
                   if(dms.getWidth() == dm.getWidth() &&
                   dms[i].getHeight() == dm.getHeight() &&
                   dms[i].getBitDepth() == dm.getBitDepth())
                        return true;
              return false;
         public static boolean isValidDefaultDisplayMode(DisplayMode dm)
              return isValidDisplayMode(getDefaultGraphicsDevice(), dm);
         //class methods
         public boolean isFullScreenSupported()
              return gd.isFullScreenSupported();
         public boolean isDisplayChangeSupported()
              return gd.isDisplayChangeSupported();
         public void initFullscreen() throws Screen.FullScreenInitException
              if(!isFullScreenSupported() || !isDisplayChangeSupported())
                   throw new Screen.FullScreenInitException();
              //init the display
              gd.setDisplayMode(newDisplayMode);
              gd.setFullScreenWindow(mainFrame);
              mainFrame.createBufferStrategy(3);
              bs = mainFrame.getBufferStrategy();
         public void deinitFullscreen()
              gd.setFullScreenWindow(null);
              gd.setDisplayMode(oldDisplayMode);
         public Frame getBaseFrame()
              return mainFrame;
         public GraphicsConfiguration getCurrentGraphicsConfiguration()
              return mainFrame.getGraphicsConfiguration();
         public void dispose()
              mainFrame.dispose();
              mainFrame.removeNotify();
         //Draw method one: Pass in an image of the screen
         public void bltImage(Image i)
              Graphics g = bs.getDrawGraphics();
              g.setColor(Color.BLACK);
              g.fillRect(0,0, newDisplayMode.getWidth(), newDisplayMode.getHeight());
              g.drawImage(i, 0, 0, null);
              g.dispose();
              bs.show();
         //Draw method two: Get the back buffer, do you buisness, then initiate the blt
         public Graphics2D getGrahphics2D()
              Graphics2D g = (Graphics2D)bs.getDrawGraphics();
              g.setColor(Color.BLACK);
              g.fillRect(0,0, newDisplayMode.getWidth(), newDisplayMode.getHeight());
              return g;
         public void bltGraphics2D(Graphics2D g)
              bs.show();
              g.dispose();
         public class FullScreenInitException extends Exception {}

    Hi there,
    Did you ever resolve this problem? I am new to the Fullscreen API but I am writing a complicated interactive screensaver. It works really well on Windows XP but there is terrible startup flicker on OS X. My own graphics is repeatedly overdrawn with a blank white screen, about four or five times over a few seconds, then finally the window starts behaving (nearly) as expected. The same drawing code works well in a windowed version on OS X.
    Anyone else have this problem?

  • Draw a CGRect

    How do I draw a CGRect on the screen? Im making a game with collision detection and right now I have UIImageViews colliding but I want to make a smaller, more forgiving, rectangle to use with the collision detection. I just want to draw it on the screen for debugging reasons. thanks

    johosher wrote:
    How do I draw a CGRect on the screen?
    To draw 2D shapes on a view you just need to make a subclass of UIView, override the drawRect method, and use Quartz (Core Graphics) drawing functions. Here's an example that draws a rectangle on a view based on a CGRect ivar:
    // JoshView.h
    #import <UIKit/UIKit.h>
    @interface JoshView : UIView {
    CGRect myRect;
    @property (nonatomic, assign) CGRect myRect;
    @end
    // JoshView.m
    #import "JoshView.h"
    @implementation JoshView
    @synthesize myRect;
    - (void)drawRect:(NSRect)rect {
    // Drawing code here.
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(c, 1.0, 0.0, 0.5, 1.0);
    CGContextFillRect(c, myRect);
    @end
    // JoshViewController.m
    #import "JoshViewController.h"
    #import "JoshView.h"
    @implementation JoshViewController
    // Implement viewDidLoad to do additional setup after loading the view.
    - (void)viewDidLoad {
    [super viewDidLoad];
    [(JoshView*)self.view setMyRect:CGRectMake(120, 120, 80, 80)];
    [self.view setNeedsDisplay];
    @end
    - Ray

  • Keeping an oft-redrawn interface interactive by preparing drawing in thread

    Hi!
    I require rapid updates (say, every 0.1 s) to several UIViews which reflect the state of constantly-changing model objects. Doing the updates on the main thread blocks the interface pretty quickly, so I tried to move the main drawing code to a thread which renders to an image, which is then drawn later on the main thread.
    I'm getting EXCBADACCESS errors on -\[UIImage drawAtPoint:\], however.
    CGSize size = \[self frame\].size;
    UIGraphicsBeginImageContext(size);
    UIImage *img = \[UIImage imageNamed:@"MyImage.png"\];
    [img drawAtPoint:CGPointZero]; // EXCBADACCESS here
    And the backtrace:
    #0 0x3104ee65 in CGSBlendBGRA8888toARGB8888 ()
    #1 0x31186b49 in rgba32_image ()
    #2 0x00560e12 in ripl_Mark ()
    #3 0x00563328 in ripl_BltImage ()
    #4 0x0054e9d1 in ripc_RenderImage ()
    #5 0x0055d997 in ripc_DrawImage ()
    #6 0x30fef3f5 in CGContextDrawImage ()
    #7 0x30a676ba in -\[UIImage drawInRect:blendMode:alpha:\] ()
    #8 0x30a65013 in -\[UIImage drawAtPoint:blendMode:alpha:\] ()
    #9 0x30a64f92 in -\[UIImage drawAtPoint:\] ()
    I also noticed that I'm sometimes getting EXCBADACCESS on the main thread, in unrelated drawing code. It would appear that the creation of the image context is app-global, and causing trouble for other drawing routines.
    So, my question is this: What's the accepted solution to keep an interface interactive, while providing frequent view updates? If I was writing an OS X app, I'd do the above, using -\[NSImage lockFocus\] and -\[NSImage unlockFocus\]. No joy here, though!
    It seems my only path at this point is to do the compositing manually, with the underying char arrays of the bitmap images. That's nasty, though.
    Many thanks in advance

    I'm not reading that either, but to help you for next time:
    - use more than 1 sentence to describe your problem
    - only post the RELEVANT code, or a small test program with the same problem if possible.
    At least you formatted it, I'll give you that.
    Cheers,
    Radish21
    PS. I think in this case, posting another (better worded) thread might be a good idea, because no one is going to read this one. In general though, don't :)

  • Resize of Drawing in JPanel

    Hi,
    I am looking for some ideas on how to resize a drawing in JPanel.
    I wanted to increase its width and height at run time by dragging its end points (any direction).
    One more thing is how do I add text to the drawing at run time? Is this possible?
    My idea is to develop an application similar to MS-Word where we can add few drawings and add text to them.
    Any help would be great.
    Mathew

    The drawing code has to be written in ratios. Don't draw from x1, y1, to x2, y2 -- draw from (left + .3*width, top + .3 * height) to . . . Then the drag gesture should give you new width and height values, and you can just repaint().

Maybe you are looking for

  • Re: if weblogic can serve two ports at the same time?

    That's not true. WebLogic supports a non-secure and secure listener port at the same time. That was one of the selling points for my organization. Michael Girdley wrote: If, you mean the same port on two different IP addresses, then the answer is yes

  • Hp officejet 6500 wireless doesn't scan to pdf and can't install driver

    Purchased a new Windows 8.1 laptop (Dell) and using my old 6500 wireless printer but connected directly through USB.  I can scan from the printer control panel, but don't see an option to save the output as a pdf as was formerly the case with my Wind

  • Solaris intel (x86) DCA not saving when rebooted.

    I'm working with a Panasonic CF-71 toughbook laptop. I have loaded the 2.6 Solaris intel OS and the Xig PCMCIA patch. I have been successful in getting a 3Com 3C589D card to work, but only if I enter into DCA at boot time and delete the PnP ISA PCMCI

  • Smartforms in ECC 6.0

    Hi Folks, I am designing a smartforms for invoice but the drag and drop opertaion doesn't work in ECC 6.0 version how do i insert fields using field list generator.. any help wud be appreciated.

  • Installing Demostration Schemas: HR and OE Schemas

    I recently purchased the SQL Fundamentals I Exam Guide. In the book, it says that I can find the demo.s chemas on the CD's. Will the schemas be included in the downloadable 11g version found on Oracle's website?! If not, is there any other ways to in