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

Similar Messages

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

  • 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

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • 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

  • Inset bevel on stacked canvas - is it possible?

    Hello.
    I want to create a stacked canvas with an inset bevel, but when I
    run the form the
    inset bevel is not shown. The only bevels that shows is lovered
    and raised.
    Does anyone know how to get an inset bevel to show, so that the
    stacked canvas
    apears as a scrolling region within a frame with inset bevel?
    -Peter
    null

    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

  • Need Help: Trying to remove last shapes from canvas

    I'm trying to move the last shapes from canvas using jButton. when i click on button it doesnt do anything but when i click on that shape it does remove it...can anyone please help me here .. i dont see anythign wrong with it..but may be you guys can
    public void actionPerformed(ActionEvent e) {
    if ( e.getSource() == jbtRemove)
         pane.removeLastShape();
    public void removeLastShape(){
    int numberShapes = shapes.size();
    if(numberShapes > 0){
         shapes.removeElementAt( numberShapes - 1 );
    }

    You need to repaint the canvas in your actionPerformed method so the changes will take affect.

  • My repaint() method flickers

    Hi, can someone help me enhance my GUI so that it won't flicker? I tried to use BufferStrategy but it still flickers. I used the code below to override the repaint method of the Canvas that I am trying to draw. Also, I'm not really sure if the repaint() method was the right method to override.
    public void repaint() {
              super.repaint();
              this.createBufferStrategy(2);
              BufferStrategy bufferStrategy = this.getBufferStrategy();
              Graphics g = bufferStrategy.getDrawGraphics();
              g.setColor(Color.BLACK);
                    //x and y are changed by a different Thread every 1 millisecond
              g.drawOval(x, y, 20, 20);
              g.dispose();
              bufferStrategy.show();
         }I also have another Thread that repaints my Canvas.
    public class Painter implements Runnable {
         private LandAreaCanvas area;
         public Painter(LandAreaCanvas area) {
              this.area = area;
         public void run() {
              while (true) {
                   area.repaint();
    }So in summary, my application has 3 Threads running
    1. Main class with main method that initializes all GUI components
    2. Painter class that repaints forever
    3. Calculator class that changes the value of x and y in the repaint method of the Canvas class.
    Thanks a lot!

    Actually you should do your custom painting by overriding paintComponent(Graphics). Which should not flicker since Swing uses double buffering by default.
    See [the tutorial|http://java.sun.com/docs/books/tutorial/uiswing/painting/].
    On edit looks like you might be using AWT, so above advice might not be relevant. [The linked article|http://java.sun.com/products/jfc/tsc/articles/painting/] in the tutorial still can be of help though.
    Edited by: WalterLaan on May 7, 2009 2:13 AM

  • Balls don't move in bouncing balls game.Please Help !?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package ****;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("****");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  This code draws only the first position of the ball:
    http://img267.imageshack.us/my.php?image=51649094by6.jpg

    I'm trying to draw everything first to a buffer:
    buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
    gBuffer=buffer.getGraphics();
    The buffer is for one JPanel and then i want to draw this buffer every time when balls change their possitions(collide or just move).
    The logic is something like this:
    startButton -> (ball.start() and add ball to List<balls>),
    ball.start() -> ball.run() -> (move allballs, paint to buffer and show buffer)
    In the first class:
    BouncingBalls balls; //A REFERENCE TO SECOND CLASS
    In the second class:
    private List<CollideBall> balls=new ArrayList();
    the tames are the same but this isn't an error.
    Edited by: vigour on Feb 14, 2008 7:57 AM

  • I need help to draw an image and move it plz plz : )

    Ok, so I have this whole code and I understand most of it but not all of it but I'm trying to make image "drop.gif" to move down the right side of the window. For each shot that is taken the image moves down ever so much and if the image hits the Entity ship "background" than notify death. PLease anyone help me !
    there are 7 classes but here is the main ...
    package spaceinvaderss;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Main extends Canvas {
    /*A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.
    An application must subclass the Canvas class in order to get useful functionality such as creating a custom component.
    The paint method must be overridden in order to perform custom graphics on the canvas.*/
    /** The stragey that allows us to use accelerate page flipping.*/
    private BufferStrategy strategy;
    /** True if the game is currently "running", i.e. the game loop is looping */
    private boolean gameRunning = true;
    /** The list of all the entities that exist in our game */
    private ArrayList entities = new ArrayList();
    /** The list of entities that need to be removed from the game this loop */
    private ArrayList removeList = new ArrayList();
    /** The entity representing the player */
    private Entity ship;
    /** The entity representing the alien */
    private Entity alien;
    /** The speed at which the player's ship should move (pixels/sec) */
    private double moveSpeed = 600;
    /** The time at which last fired a shot */
    private long lastFire = 0;
    /** The interval between our players shot (ms) */
    private long firingInterval = 400;
    /** timer */
    private long time = 0;
    /** The number of aliens left on the screen */
    private int alienCount;
    /** The message to display which waiting for a key press */
    private String message = "";
    /** True if we're holding up game play until a key has been pressed */
    private boolean waitingForKeyPress = true;
    /** True if the left cursor key is currently pressed */
    private boolean leftPressed = false;
    /** True if the right cursor key is currently pressed */
    private boolean rightPressed = false;
    /** True if we are firing */
    private boolean firePressed = false;
    /** True if game logic needs to be applied this loop, normally as a result of a game event */
    private boolean logicRequiredThisLoop = false;
    private static Image drop;
    /** The constant for the width*/
    private int DOMAIN = 800;
    /** The constant fot the length*/
    private int RANGE = 950;
    /** The constant for the number of rows of aliens */
    private int numbaofrows = 8;
    /** The constant for the number of aliens per row */
    private int aliensperrow = 12;
    /** The constant for the percent of which the speed increases*/
    private double speedincrease = 1.02;
    /** Starts the variable that counts the shots*/
    private int shotsfired = 0;
    /** Construct our game and set it running.*/
    public Main() {
    // Creates a frame to contain Main.
    JFrame container = new JFrame("SPACE INVADERS !!! WOOT !!! WOOT !!!");
    // Gets a hold of the content of the frame and sets up the resolution of the game
    // Names the inside of the "container" as panel.
    JPanel panel = (JPanel) container.getContentPane();
    // Stes the demensions of the panel.
    panel.setPreferredSize(new Dimension(DOMAIN,RANGE));
    //Sets the layout as nothing which overrides any automatic properties.
    panel.setLayout(null);
    // Sets up our canvas size and puts it into the content of the frame
    setBounds(0, 0, DOMAIN, RANGE);
    panel.add(this);
    // Tell AWT not to bother repainting our canvas since we're
    // going to do that our self in accelerated mode.
    setIgnoreRepaint(true);
    // Actually sizes the window approximately.
    container.pack();
    // Makes it so that the window can't be resized.
    container.setResizable(false);
    // Makes the window visible.
    container.setVisible(true);
    // Add a listener to respond to the user pressing the x.
    // End the program when the window is closed.
    container.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add a key input system (defined below) to our canvas
    // so we can respond to key pressed
    addKeyListener(new KeyInputHandler());
    // request the focus so key events come to us
    requestFocus();
    // Create the buffering strategy which will allow AWT
    // to manage our accelerated graphics.
    createBufferStrategy(2);
    strategy = getBufferStrategy();
    // initialise the entities in our game so there's something
    // to see at startup
    initEntities();
    time = System.currentTimeMillis();
    * Start a fresh game, this should clear out any old data and
    * create a new set.
    private void startGame() {
    // clear out any existing entities and intialise a new set
    entities.clear();
    initEntities();
    // blank out any keyboard settings we might currently have
    leftPressed = false;
    rightPressed = false;
    firePressed = false;
    * Initialise the starting state of the entities (ship and aliens). Each
    * entitiy will be added to the overall list of entities in the game.
    private void initEntities() {
    ClassLoader cloader = Main.class.getClassLoader();
    drop = Toolkit.getDefaultToolkit().getImage(cloader.getResource("drop.gif"));
    prepareImage(drop, this);
    // create the player ship and place it in the center of the screen
    ship = new ShipEntity(this,"background.gif", 0, (RANGE - 75));
    entities.add(ship);
    ship = new ShipEntity(this,"ship.gif", (DOMAIN / 2) - 0, (RANGE - 50));
    entities.add(ship);
    // create a block of aliens
    alienCount = 0;
    for (int row = 0; row < numbaofrows; row++) {
    for (int x = 0; x < aliensperrow; x++) {
    alien = new AlienEntity(this,"alien.gif", 100 + (x*50),(50)+row*30);
    entities.add(alien);
    alienCount++;
    * Notification from a game entity that the logic of the game
    * should be run at the next opportunity (normally as a result of some
    * game event)
    public void updateLogic() {
    logicRequiredThisLoop = true;
    * Remove an entity from the game. The entity removed will
    * no longer move or be drawn.
    * Remove the entity
    public void removeEntity(Entity entity) {
    removeList.add(entity);
    /**Notify that the player has died.*/
    public void notifyDeath() {
    message = "Oh no! The aliens win, wanna try again?";
    waitingForKeyPress = true;
    /** Notification that the player has won since all the aliensare dead.*/
    public void notifyWin() {
    long time2;
    time2 = (System.currentTimeMillis() - time) / 1000;
    int acuracy = 1000*(aliensperrow*numbaofrows)/shotsfired;
    message = "Congradulations! You win! Your time was: " + time2 + " seconds. Your acuracy was " + acuracy + "%.";
    waitingForKeyPress = true;
    /**Notification that an alien has been killed*/
    public void notifyAlienKilled() {
    // reduce the alient count, if there are none left, the player has won!
    alienCount--;
    if (alienCount == 0) {
    notifyWin();
    // if there are still some aliens left then they all need to get faster, so
    // speed up all the existing aliens
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    if (entity instanceof AlienEntity) {
    // speed up every time the aliens move down
    entity.setHorizontalMovement(entity.getHorizontalMovement() * speedincrease);
    /**Attempt to fire a shot from the player. Its called "try" since we must first
    * check that the player can fire at this point, i.e. has he/she waited long
    * enough between shots.*/
    public void tryToFire() {
    // check that we have been waiting long enough to fire
    if (System.currentTimeMillis() - lastFire < firingInterval) {
    return;
    // if we waited long enough, create the shot entity, and record the time.
    lastFire = System.currentTimeMillis();
    ShotEntity shot = new ShotEntity(this, "bullet.gif", ship.getX() + 27, ship.getY() - 30);
    entities.add(shot);
    * The main game loop. This loop is running during all game
    * play as is responsible for the following activities:
    * - Working out the speed of the game loop to update moves
    * - Moving the game entities
    * - Drawing the screen contents (entities, text)
    * - Updating game events
    * - Checking Input
    public void gameLoop() {
    long lastLoopTime = System.currentTimeMillis();
    // Keep looping around till the game ends.
    while (gameRunning) {
    // Work out how long its been since the last update, this
    // will be used to calculate how far the entities should
    // move this loop.
    long delta = System.currentTimeMillis() - lastLoopTime;
    lastLoopTime = System.currentTimeMillis();
    // Get hold of a graphics context for the accelerated
    // surface and black it out.
    Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
    g.setColor(Color.black);
    g.fillRect(0, 0, DOMAIN, RANGE);
    // Cycle around asking for each entity to move itself.
    if (!waitingForKeyPress) {
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.move(delta);
    // cycle round drawing all the entities we have in the game
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.draw(g);
    // brute force collisions, compare every entity against
    // every other entity. If any of them collide notify
    // both entities that the collision has occured
    for (int p = 0; p < entities.size(); p++) {
    for (int s = p + 1; s < entities.size(); s++) {
    Entity me = (Entity) entities.get(p);
    Entity him = (Entity) entities.get(s);
    if (me.collidesWith(him)) {
    me.collidedWith(him);
    him.collidedWith(me);
    // remove any entity that has been marked for clear up
    entities.removeAll(removeList);
    removeList.clear();
    // if a game event has indicated that game logic should
    // be resolved, cycle round every entity requesting that
    // their personal logic should be considered.
    if (logicRequiredThisLoop) {
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.doLogic();
    logicRequiredThisLoop = false;
    // if we're waiting for an "any key" press then draw the
    // current message
    if (waitingForKeyPress) {
    g.setColor(Color.green);
    g.drawString(message,(DOMAIN-g.getFontMetrics().stringWidth(message)) / 2, 250);
    g.drawString("TO PLAY, PRESS ANY KEY : )", (DOMAIN-g.getFontMetrics().stringWidth("TO PLAY, PRESS ANY KEY : )")) / 2, 40);
    // Clear up the graphics.
    g.dispose();
    // Flip the buffer over.
    strategy.show();
    // resolve the movement of the ship. First assume the ship
    // isn't moving. If either cursor key is pressed then
    // update the movement appropraitely
    ship.setHorizontalMovement(0);
    if ((leftPressed) && (!rightPressed)) {
    ship.setHorizontalMovement(-moveSpeed);
    } else if ((rightPressed) && (!leftPressed)) {
    ship.setHorizontalMovement(moveSpeed);
    // if we're pressing fire, attempt to fire
    if (firePressed) {
    shotsfired++;
    tryToFire();
    // finally pause for a bit. Note: this should run us at about
    // 100 fps but on windows this might vary each loop due to
    // a bad implementation of timer
    try { Thread.sleep(10); } catch (Exception e) {}
    * A class to handle keyboard input from the user. The class
    * handles both dynamic input during game play, i.e. left/right
    * and shoot, and more static type input (i.e. press any key to
    * continue)
    * This has been implemented as an inner class more through
    * habbit then anything else. Its perfectly normal to implement
    * this as seperate class if slight less convienient.
    private class KeyInputHandler extends KeyAdapter {
    /** The number of key presses we've had while waiting for an "any key" press */
    private int pressCount = 1;
    * Notification from AWT that a key has been pressed. Note that
    * a key being pressed is equal to being pushed down but NOT
    * released. Thats where keyTyped() comes in.
    * @param e The details of the key that was pressed
    public void keyPressed(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "press"
    if (waitingForKeyPress) {
    return;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = true;
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = true;
    * Notification from AWT that a key has been released.
    * @param e The details of the key that was released
    public void keyReleased(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "released"
    if (waitingForKeyPress) {
    return;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = false;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = false;
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = false;
    * Notification from AWT that a key has been typed. Note that
    * typing a key means to both press and then release it.
    * @param e The details of the key that was typed.
    public void keyTyped(KeyEvent e) {
    // if we're waiting for a "any key" type then
    // check if we've recieved any recently. We may
    // have had a keyType() event from the user releasing
    // the shoot or move keys, hence the use of the "pressCount"
    // counter.
    if (waitingForKeyPress) {
    if (pressCount == 1) {
    // since we've now recieved our key typed
    // event we can mark it as such and start
    // our new game
    waitingForKeyPress = false;
    startGame();
    pressCount = 0;
    } else {
    pressCount++;
    // if we hit escape, then quit the game
    if (e.getKeyChar() == 27) {
    System.exit(0);
    * The entry point into the game. We'll simply create an
    * instance of class which will start the display and game
    * loop.
    * @param argv The arguments that are passed into our game
    public static void main(String argv[]) {
    Main g = new Main();
    // Starts the main game loop, this method will not return until the game has finished running. Hence we are
    // using the actual main thread to run the game.
    g.gameLoop();
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Ap_Compsci_student_13 wrote:
    ok sorry but doesn't sscce say to post the whole code?the first S is Short, and yes, it needs to be all the code needed to illustrate the problem and let use reproduce it. If you were developing a new Web framework, your example might be short, but for a student game it's very long.

  • JPanel loses keyboard focus

    Ok, i have a JTextField which is initially disabled. A JPanel draws some stuff and receives keyboard input. When i enable the textfield, type some stuff, then press Esc (which disables it), i cant get the keyboard focus back on the JPanel. Here is an example:
    (you can move the red circle before you enable the textfield, after you disable it, you cant move it anymore).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.util.Vector;
    public class example extends JPanel implements ActionListener,Runnable {
        JFrame frame;
        JMenuBar menubar;
        JMenu m_file;
        JMenuItem mi_open,mi_close;
        JPanel canvas,northpanel;
        JTextField textfield;
        Image canvasimg;
        Thread thread=new Thread(this);
        private Image dbImage;     // for flickering
         private Graphics dbg;     // for flickering
         int x1=400,y1=200;
        public example() {
            frame = new JFrame("Example");                         // window
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1000,700));
            frame.setLayout(new BorderLayout());
            northpanel=new JPanel();
            northpanel.setLayout(null);
            northpanel.setPreferredSize(new Dimension(1000,20));     northpanel.setLocation(0,0);
            menubar=new JMenuBar();
            m_file=new JMenu("File");   
            mi_open=new JMenuItem("Open");
            mi_close=new JMenuItem("Close");
            m_file.add(mi_open);
            m_file.add(mi_close);   
            m_file.getPopupMenu().setLightWeightPopupEnabled(false);   
            menubar.add(m_file);
            northpanel.add(menubar);
            menubar.setLocation(0,0);     menubar.setSize(80,20);
            textfield=new JTextField();
            northpanel.add(textfield);
            textfield.setSize(200,20);     textfield.setLocation(500,0);   
            textfield.setEnabled(false);
            frame.add(northpanel,BorderLayout.NORTH);
            canvas=new JPanel();
            canvas.setLayout(null);
            canvas.setSize(1000,600);
            canvas.setBackground(Color.white);
             frame.add(canvas,BorderLayout.CENTER);      
            frame.pack();
            frame.setVisible(true);       
            thread.start();                                   // start the thread
            textfield.addMouseListener(new MouseAdapter(){
                    public void mousePressed(MouseEvent e){
                         textfield.setEnabled(true);
               textfield.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){
                      int key=e.getKeyCode();
                      if(key==27){     // esc
                           textfield.setEnabled(false); 
                           canvas.setEnabled(true);                // not working
                           canvas.requestFocus();
                           canvas.requestFocusInWindow();
               frame.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){                   
                      int key=e.getKeyCode();
                      if(key==37){ //left
                           x1-=5;
                      if(key==38){ //up
                           y1-=5;
                      if(key==39){ //right
                           x1+=5;
                      if(key==40){ //down
                           y1+=5;
        // Create the GUI and show it. 
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            example ex = new example();
        public void run(){
             while(true){
                  try{
                       if(canvasimg==null)repaint();                   
                       Graphics g=canvas.getGraphics();
                       update(g);
                       thread.sleep(30);                                             // 1 sec
                  }      catch(InterruptedException ex){}
        // ActionPerformed handles button and menu events
        public void actionPerformed(ActionEvent e){              
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void update (Graphics g){          // get rid of flicker
              if (dbImage == null){
                   dbImage = canvas.createImage (canvas.getSize().width, canvas.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (canvas.getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (canvas.getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void paint(Graphics g){
              g.drawImage(canvasimg,0,0,this);          
              g.setColor(Color.red);
             g.fillOval(x1,y1,10,10);
        public void repaint(){     
             if(canvas!=null && canvasimg==null)canvasimg=canvas.createImage(1000,670);
             if(canvasimg==null)return;
             Graphics g=canvasimg.getGraphics();
             if(g==null)return;
             g.setColor(Color.white);
             g.fillRect(0,0,1000,600);
    }  

    OK great guru since you're so damn confident that you're doing everything right, find out for yourself why this works and yours doesn't.
    I could list a few dozen things wrong with your code, but I'd be wasting my keystrokes.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TextFieldDisableNoProblem extends JPanel {
       JPanel northPanel;
       JMenuBar menubar;
       JMenu m_file;
       JMenuItem mi_open,mi_close;
       JTextField textField;
       int x1 = 400;
       int y1 = 200;
       public TextFieldDisableNoProblem () {
          setBackground (Color.WHITE);
          addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                switch (key) {
                   case KeyEvent.VK_LEFT:
                         x1 -= 5;
                         break;
                   case KeyEvent.VK_UP:
                         y1 -= 5;
                         break;
                   case KeyEvent.VK_RIGHT:
                         x1 += 5;
                         break;
                   case KeyEvent.VK_DOWN:
                         y1 += 5;
                         break;
                repaint ();
       void makeUI () {
          JFrame frame = new JFrame ("");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (600, 500);
          frame.setLocationRelativeTo (null);
          menubar=new JMenuBar ();
          m_file=new JMenu ("File");
          mi_open=new JMenuItem ("Open");
          mi_close=new JMenuItem ("Close");
          m_file.add (mi_open);
          m_file.add (mi_close);
          menubar.add (m_file);
          frame.setJMenuBar (menubar);
          textField=new JTextField ();
          textField.setEnabled (false);
          textField.setBounds (200, 0, 200, 20);
          textField.addMouseListener (new MouseAdapter (){
             public void mousePressed (MouseEvent e){
                textField.setEnabled (true);
          textField.addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                if(key == KeyEvent.VK_ESCAPE){
                   textField.setEnabled (false);
                   requestFocus ();
          northPanel=new JPanel ();
          northPanel.setLayout (null);
          northPanel.setPreferredSize (new Dimension (600,20));
          northPanel.add (textField);
          frame.add (northPanel,BorderLayout.NORTH);
          frame.add (this, BorderLayout.CENTER);
          frame.setVisible (true);
          requestFocus ();
       public void paintComponent (Graphics g) {
          super.paintComponent (g);
          g.setColor (Color.RED);
          g.fillOval (x1, y1, 10, 10);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                JFrame.setDefaultLookAndFeelDecorated (true);
                new TextFieldDisableNoProblem ().makeUI ();
    }db

  • Storing Shape Information IN a Table-Like Structure

    Hi All,
    I have a Program which displays shape (rectangle,oval,etc) in the panel which is enclosed in a frame.. shape can be dragged and dropped anywhere on panel... also one can delete shape... Now I Want To Store All The Exiting Shapes (as they are added on panel ) in some structure say a table, and alongwith it, i also want to store additional information about shape, say its location currently on panel, its present color, etc so that i can use this information later in the program... how do i do implement this ?? Plz Help Me.. It would be great if you include the changes in the source code itself...
    thanks
    Here is the source code :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class ShapeDrawFrame extends javax.swing.JFrame {
        JCheckBoxMenuItem addLargeShapes;    
       JCheckBoxMenuItem addBorderedShapes; 
       JRadioButtonMenuItem red, green, blue,      
                            cyan, magenta, yellow, 
                            black, gray, white;  
       JPopupMenu popup;
        public ShapeDrawFrame() {
            super("Shape Draw");
            //initComponents();        
          ShapeCanvas canvas = new ShapeCanvas();
          setContentPane(canvas);
          /* Create the menu bar and the menus */
          JMenuBar menubar = new JMenuBar();
          setJMenuBar(menubar);
          JMenu addShapeMenu = new JMenu("Add");
          addShapeMenu.setMnemonic('A');
          menubar.add(addShapeMenu);
          JMenu shapeColorMenu = new JMenu("Color");
          shapeColorMenu.setMnemonic('C');
          menubar.add(shapeColorMenu);
          JMenu optionsMenu = new JMenu("Options");
          optionsMenu.setMnemonic('O');
          menubar.add(optionsMenu);
          /* Create menu items for adding shapes to the canvas,
             and add them to the "Add" menu.  The canvas serves
             as ActionListener for these menu items. */     
          JMenuItem rect = new JMenuItem("Rectangle");
          rect.setAccelerator( KeyStroke.getKeyStroke("ctrl R") );
          addShapeMenu.add(rect);
          rect.addActionListener(canvas);
          JMenuItem oval = new JMenuItem("Oval");
          oval.setAccelerator( KeyStroke.getKeyStroke("ctrl O") );
          addShapeMenu.add(oval);
          oval.addActionListener(canvas);
          JMenuItem roundrect = new JMenuItem("Round Rect");
          roundrect.setAccelerator( KeyStroke.getKeyStroke("ctrl D") );
          addShapeMenu.add(roundrect);
          roundrect.addActionListener(canvas);
          /* Create the JRadioButtonMenuItems that control the color
             of a newly added shape, and add them to the "Color"
             menu.  There is no ActionListener for these menu items.
             The canvas checks for the currently selected color when
             it adds a shape to the canvas.  A ButtonGroup is used
             to make sure that only one color is selected. */
          ButtonGroup colorGroup = new ButtonGroup();
          red = new JRadioButtonMenuItem("Red");
          shapeColorMenu.add(red);
          colorGroup.add(red);
          red.setSelected(true);
          green = new JRadioButtonMenuItem("Green");
          shapeColorMenu.add(green);
          colorGroup.add(green);
          blue = new JRadioButtonMenuItem("Blue");
          shapeColorMenu.add(blue);
          colorGroup.add(blue);
          cyan = new JRadioButtonMenuItem("Cyan");
          shapeColorMenu.add(cyan);
          colorGroup.add(cyan);
          magenta = new JRadioButtonMenuItem("Magenta");
          shapeColorMenu.add(magenta);
          colorGroup.add(magenta);
          yellow = new JRadioButtonMenuItem("Yellow");
          shapeColorMenu.add(yellow);
          colorGroup.add(yellow);
          black = new JRadioButtonMenuItem("Black");
          shapeColorMenu.add(black);
          colorGroup.add(black);
          gray = new JRadioButtonMenuItem("Gray");
          shapeColorMenu.add(gray);
          colorGroup.add(gray);
          white = new JRadioButtonMenuItem("White");
          shapeColorMenu.add(white);
          colorGroup.add(white);
          /* Create the "Clear" menu item, and add it to the
             "Options" menu.  The canvas will listen for events
             from this menu item. */
          JMenuItem clear = new JMenuItem("Clear");
          clear.setAccelerator( KeyStroke.getKeyStroke("ctrl C") );
          clear.addActionListener(canvas);
          optionsMenu.add(clear);
          optionsMenu.addSeparator();  // Add a separating line to the menu.
          /* Create the JCheckBoxMenuItems and add them to the Options
             menu.  There is no ActionListener for these items because
             the canvas class will check their state when it adds a
             new shape. */
          addLargeShapes = new JCheckBoxMenuItem("Add Large Shapes");
          addLargeShapes.setSelected(true);
          optionsMenu.add(addLargeShapes);
          addBorderedShapes = new JCheckBoxMenuItem("Add Shapes with Border");
          addBorderedShapes.setSelected(true);
          optionsMenu.add(addBorderedShapes);
          optionsMenu.addSeparator();
          /* Create a menu for background colors, and add it to the
             "Options" menu.  It will show up as a hierarchical sub-menu. */
          JMenu background = new JMenu("Background Color");
          optionsMenu.add(background);
          background.add("Red").addActionListener(canvas);
          background.add("Green").addActionListener(canvas);
          background.add("Blue").addActionListener(canvas);
          background.add("Cyan").addActionListener(canvas);
          background.add("Magenta").addActionListener(canvas);
          background.add("Yellow").addActionListener(canvas);
          background.add("Black").addActionListener(canvas);
          background.add("Gray").addActionListener(canvas);
          background.add("White").addActionListener(canvas);
          /* Create the pop-up menu and add commands for editing a
             shape.  This menu is not used until the user performs
             the pop-up trigger mouse gesture on a shape. */
          popup = new JPopupMenu();
          popup.add("Delete Shape").addActionListener(canvas);
          popup.add("Bring to Front").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Make Large").addActionListener(canvas);
          popup.add("Make Small").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Add Black Border").addActionListener(canvas);
          popup.add("Remove Black Border").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Set Color to Red").addActionListener(canvas);
          popup.add("Set Color to Green").addActionListener(canvas);
          popup.add("Set Color to Blue").addActionListener(canvas);
          popup.add("Set Color to Cyan").addActionListener(canvas);
          popup.add("Set Color to Magenta").addActionListener(canvas);
          popup.add("Set Color to Yellow").addActionListener(canvas);
          popup.add("Set Color to Black").addActionListener(canvas);
          popup.add("Set Color to Gray").addActionListener(canvas);
          popup.add("Set Color to White").addActionListener(canvas);
          /* Set the "DefaultCloseOperation" for the frame.  This determines
             what happens when the user clicks the close box of the frame.
             It is set here so that System.exit() will be called to end
             the program when the user closes the window. */
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          /* Set the size and location of the frame, and make it visible. */
          setLocation(20,50);
          setSize(550,420);
          show();       
       class ShapeCanvas extends JPanel
                         implements ActionListener, 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.
          ArrayList shapes = new ArrayList();
               // holds a list of the shapes that are displayed on the canvas
          ShapeCanvas() {
               // Constructor: set background color to white
               // set up listeners to respond to mouse actions
             setBackground(Color.white);
             addMouseListener(this);
             addMouseMotionListener(this);
          public void paintComponent(Graphics g) {
               // In the paint method, all the shapes in ArrayList are
               // copied onto the canvas.
             super.paintComponent(g);  // First, fill with background color.
             int top = shapes.size();
             for (int i = 0; i < top; i++) {
                Shape s = (Shape)shapes.get(i);
                s.draw(g);
          public void actionPerformed(ActionEvent evt) {
                 // Called to respond to action events from the
                 // menus or pop-up menu.
             String command = evt.getActionCommand();
             if (command.equals("Clear")) {
                shapes.clear(); // Remove all items from the ArrayList
                repaint();
             else if (command.equals("Rectangle"))
                addShape(new RectShape());
             else if (command.equals("Oval"))
                addShape(new OvalShape());
             else if (command.equals("Round Rect"))
                addShape(new RoundRectShape());
             else if (command.equals("Red"))
                setBackground(Color.red);
             else if (command.equals("Green"))
                setBackground(Color.green);
             else if (command.equals("Blue"))
                setBackground(Color.blue);
             else if (command.equals("Cyan"))
                setBackground(Color.cyan);
             else if (command.equals("Magenta"))
                setBackground(Color.magenta);
             else if (command.equals("Yellow"))
                setBackground(Color.yellow);
             else if (command.equals("Black"))
                setBackground(Color.black);
             else if (command.equals("Gray"))
                setBackground(Color.gray);
             else if (command.equals("White"))
                setBackground(Color.white);
             else if (clickedShape != null) {
                    // Process a command from the pop-up menu.
                if (command.equals("Delete Shape"))
                   shapes.remove(clickedShape);
                else if (command.equals("Bring to Front")) {
                   shapes.remove(clickedShape);
                   shapes.add(clickedShape); 
                else if (command.equals("Make Large"))
                   clickedShape.setSize(100,60);
                else if (command.equals("Make Small"))
                   clickedShape.setSize(50,30);
                else if (command.equals("Add Black Border"))
                   clickedShape.setDrawOutline(true);
                else if (command.equals("Remove Black Border"))
                   clickedShape.setDrawOutline(false);
                else if (command.equals("Set Color to Red"))
                   clickedShape.setColor(Color.red);
                else if (command.equals("Set Color to Green"))
                   clickedShape.setColor(Color.green);
                else if (command.equals("Set Color to Blue"))
                   clickedShape.setColor(Color.blue);
                else if (command.equals("Set Color to Cyan"))
                   clickedShape.setColor(Color.cyan);
                else if (command.equals("Set Color to Magenta"))
                   clickedShape.setColor(Color.magenta);
                else if (command.equals("Set Color to Yellow"))
                   clickedShape.setColor(Color.yellow);
                else if (command.equals("Set Color to Black"))
                   clickedShape.setColor(Color.black);
                else if (command.equals("Set Color to Gray"))
                   clickedShape.setColor(Color.gray);
                else if (command.equals("Set Color to White"))
                   clickedShape.setColor(Color.white);
                repaint();
          } // end actionPerformed()
          void addShape(Shape shape) {
                 // Add the shape to the canvas, and set its size, color
                 // and whether or not it should have a black border.  These
                 // properties are determined by looking at the states of
                 // various menu items.  The shape is added at the top-left
                 // corner of the canvas.
             if (red.isSelected())
                shape.setColor(Color.red);
             else if (blue.isSelected())
                shape.setColor(Color.blue);
             else if (green.isSelected())
                shape.setColor(Color.green);
             else if (cyan.isSelected())
                shape.setColor(Color.cyan);
             else if (magenta.isSelected())
                shape.setColor(Color.magenta);
             else if (yellow.isSelected())
                shape.setColor(Color.yellow);
             else if (black.isSelected())
                shape.setColor(Color.black);
             else if (white.isSelected())
                shape.setColor(Color.white);
             else
                shape.setColor(Color.gray);
             shape.setDrawOutline( addBorderedShapes.isSelected() );
             if (addLargeShapes.isSelected())
                shape.reshape(3,3,100,60);
             else
                shape.reshape(3,3,50,30);
             shapes.add(shape);
             repaint();
          } // end addShape()
          // -------------------- This rest of this class implements dragging ----------------------
          Shape clickedShape = null;  // This is the shape that the user clicks on.
                                      // It becomes the draggedShape is the user is
                                      // dragging, unless the user is invoking a
                                      // pop-up menu.  This variable is used in
                                      // actionPerformed() when a command from the
                                      // pop-up menu is processed.
          Shape draggedShape = 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.
          public void mousePressed(MouseEvent evt) {
                // User has pressed the mouse.  Find the shape that the user has clicked on, if
                // any.  If there is no shape at the position when the mouse was clicked, then
                // ignore this event.  If there is then one of three things will happen:
                // If the event is a pop-up trigger, then the pop-up menu is displayed, and
                // the user can select from the pop-up menu to edit the shape.  If the user was
                // holding down the shift key, then bring the clicked shape to the front, in
                // front of all the other shapes.  Otherwise, start dragging the shape.
             if (draggedShape != null) {
                  // A drag operation is already in progress, so ignore this click.
                  // This might happen if the user clicks a second mouse button before
                  // releasing the first one(?).
                return;
             int x = evt.getX();  // x-coordinate of point where mouse was clicked
             int y = evt.getY();  // y-coordinate of point
             clickedShape = null;  // This will be set to the clicked shape, if any.
             for ( int i = shapes.size() - 1; i >= 0; i-- ) { 
                    // Check shapes from front to back.
                Shape s = (Shape)shapes.get(i);
                if (s.containsPoint(x,y)) {
                   clickedShape = s;
                   break;
             if (clickedShape == null) {
                   // The user did not click on a shape.
                return;
             else if (evt.isPopupTrigger()) {
                  // The user wants to see the pop-up menu
                popup.show(this,x-10,y-2);
             else if (evt.isShiftDown()) {
                  // Bring the clicked shape to the front
                shapes.remove(clickedShape);
                shapes.add(clickedShape);
                repaint();
             else {
                  // Start dragging the shape.
                draggedShape = clickedShape;
                prevDragX = x;
                prevDragY = y;
          public void mouseDragged(MouseEvent evt) {
                 // User has moved the mouse.  Move the dragged shape by the same amount.
             if (draggedShape == null) {
                    // User did not click a shape.  There is nothing to do.
                return;
             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
          public void mouseReleased(MouseEvent evt) {
                 // User has released the mouse.  Move the dragged shape, and set
                 // draggedShape 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 on screen).  However, if the event is a popup trigger
                 // event, then show the popup menu instead.
             if (draggedShape == null) {
                   // User did not click on a shape. There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             if (evt.isPopupTrigger()) {
                   // Check whether the user is trying to pop up a menu.
                   // (This should be checked in both the mousePressed() and
                   // mouseReleased() methods.)
                popup.show(this,x-10,y-2);
             else {
                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.remove(draggedShape);  // remove shape from list of shapes
                repaint();
             draggedShape = null;  // Dragging is finished.
          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
       // ------- Nested class definitions for the abstract Shape class and three -----
       // -------------------- concrete subclasses of Shape. --------------------------
       static 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 constructed, 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 drawOutline;  // If true, a black border is drawn on the 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 setSize(int width, int height) {
                // Set the size of this shape
             this.width = width;
             this.height = height;
          void moveBy(int dx, int dy) {
                 // Move the shape by dx pixels horizontally and dy pixels vertically
                 // (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 setDrawOutline(boolean draw) {
                 // If true, a black outline is drawn around this shape.
             drawOutline = 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 behavior 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 overridden in any concrete subclass.
       }  // end of class Shape
       static class RectShape extends Shape {
             // This class represents rectangle shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRect(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRect(left,top,width,height);
       static class OvalShape extends Shape {
              // This class represents oval shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillOval(left,top,width,height);
             if (drawOutline) {
                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;
       static 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);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRoundRect(left,top,width,height,width/3,height/3);
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShapeDrawFrame().setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }

    Sure. In your original post, you had a sort of a design. The general idea was right. And then you asked us to implement it. Well, that's the wrong approach. You need to make the sort-of-a-design into a real design. Don't implement anything until you know what you are going to implement.

  • Adding sound to game application

    Can anyone assist me or provide a link as to how I can add sound to an application(non-applet)? In this case it is a space invaders clone tutorial; now I would like to add sound to when either the player or the aliens fire a laser. The problem is that I'm not sure how to do it. I initially tried using the AudioStream attribute from the sun.audio class but it did not work. Also I would like to add new images to the game background but when I add images to the panel, it does not appear when executed; the game loop I think affects this. Here is some code snippets:
    The initial setup function:
    public Game() {
              //ImagePanel p1 = new ImagePanel(new ImageIcon("City.png").getImage());
              // create a frame to contain our game
              JFrame container = new JFrame("Space Invaders 101");
              // get hold the content of the frame and set up the resolution of the game
              JPanel panel = (JPanel) container.getContentPane();
              panel.setPreferredSize(new Dimension(800,600));
              panel.setLayout(null);
              // setup our canvas size and put it into the content of the frame
              setBounds(0,0,800,600);
              panel.add(this);
              // Tell AWT not to bother repainting our canvas since we're
              // going to do that our self in accelerated mode
              setIgnoreRepaint(true);
              // finally make the window visible
              container.pack();
              container.setResizable(false);
              container.setVisible(true);
              // add a listener to respond to the user closing the window. If they
              // do we'd like to exit the game
              container.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // add a key input system (defined below) to our canvas
              // so we can respond to key pressed
              addKeyListener(new KeyInputHandler());
              // request the focus so key events come to us
              requestFocus();
              // create the buffering strategy which will allow AWT
              // to manage our accelerated graphics
              createBufferStrategy(2);
              strategy = getBufferStrategy();
              // initialise the entities in our game so there's something
              // to see at startup
              initEntities();
         }then the class for firing a shot:
    public class ShotEntity extends Entity {
         /** The vertical speed at which the players shot moves */
         private double moveSpeed = -300;
         /** The game in which this entity exists */
         private Game game;
         /** True if this shot has been "used", i.e. its hit something */
         private boolean used = false;
          * Create a new shot from the player
          * @param game The game in which the shot has been created
          * @param sprite The sprite representing this shot
          * @param x The initial x location of the shot
          * @param y The initial y location of the shot
         public ShotEntity(Game game,String sprite,int x,int y) {
              super(sprite,x,y);
              this.game = game;
              dy = moveSpeed;
          * Request that this shot moved based on time elapsed
          * @param delta The time that has elapsed since last move
         public void move(long delta) {
              // proceed with normal move
              super.move(delta);
              // if we shot off the screen, remove ourselfs
              if (y < -100) {
                   game.removeEntity(this);
          * Notification that this shot has collided with another
          * entity
          * @parma other The other entity with which we've collided
         public void collidedWith(Entity other) {
              // prevents double kills, if we've already hit something,
              // don't collide
              if (used) {
                   return;
              // if we've hit an alien, kill it!
              if (other instanceof AlienEntity) {
                   // remove the affected entities
                   game.removeEntity(this);
                   game.removeEntity(other);
                   // notify the game that the alien has been killed
                   game.notifyAlienKilled();
                   used = true;
    }The main game loop:
    public void gameLoop() {
              long lastLoopTime = System.currentTimeMillis();
              // keep looping round til the game ends
              while (gameRunning) {
                   // work out how long its been since the last update, this
                   // will be used to calculate how far the entities should
                   // move this loop
                   long delta = System.currentTimeMillis() - lastLoopTime;
                   lastLoopTime = System.currentTimeMillis();
                   // Get hold of a graphics context for the accelerated
                   // surface and blank it out
                   Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                   g.setColor(Color.black);
                   g.fillRect(0,0,800,600);
                   // cycle round asking each entity to move itself
                   if (!waitingForKeyPress) {
                        for (int i=0;i<entities.size();i++) {
                             Entity entity = (Entity) entities.get(i);
                             entity.move(delta);
                   // cycle round drawing all the entities we have in the game
                   for (int i=0;i<entities.size();i++) {
                        Entity entity = (Entity) entities.get(i);
                        entity.draw(g);
                   // brute force collisions, compare every entity against
                   // every other entity. If any of them collide notify
                   // both entities that the collision has occured
                   for (int p=0;p<entities.size();p++) {
                        for (int s=p+1;s<entities.size();s++) {
                             Entity me = (Entity) entities.get(p);
                             Entity him = (Entity) entities.get(s);
                             if (me.collidesWith(him)) {
                                  me.collidedWith(him);
                                  him.collidedWith(me);
                   // remove any entity that has been marked for clear up
                   entities.removeAll(removeList);
                   removeList.clear();
                   // if a game event has indicated that game logic should
                   // be resolved, cycle round every entity requesting that
                   // their personal logic should be considered.
                   if (logicRequiredThisLoop) {
                        for (int i=0;i<entities.size();i++) {
                             Entity entity = (Entity) entities.get(i);
                             entity.doLogic();
                        logicRequiredThisLoop = false;
                   // if we're waiting for an "any key" press then draw the
                   // current message
                   if (waitingForKeyPress) {
                        g.setColor(Color.white);
                        g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
                        g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300);
                   // finally, we've completed drawing so clear up the graphics
                   // and flip the buffer over
                   g.dispose();
                   strategy.show();
                   // resolve the movement of the ship. First assume the ship
                   // isn't moving. If either cursor key is pressed then
                   // update the movement appropraitely
                   ship.setHorizontalMovement(0);
                   if ((leftPressed) && (!rightPressed)) {
                        ship.setHorizontalMovement(-moveSpeed);
                   } else if ((rightPressed) && (!leftPressed)) {
                        ship.setHorizontalMovement(moveSpeed);
                   // if we're pressing fire, attempt to fire
                   if (firePressed) {
                        tryToFire();
                   // finally pause for a bit. Note: this should run us at about
                   // 100 fps but on windows this might vary each loop due to
                   // a bad implementation of timer
                   try { Thread.sleep(10); } catch (Exception e) {}
         

    for basic sounds, you can use the JavaSound API.
    http://java.sun.com/docs/books/tutorial/sound/index.html
    There are plugin libraries available that add MP3 and OGG support to it.
    http://www.javazoom.net/index.shtml

  • Putting a Jlabel in a specific place in JPanel

    Hi,
    I have created a JApplet where I fill it up with some JPanels. Inside a JPanel i want to put some Jlabels on a specific place. However, it doesn't work.
    Whenever i try to put a setLayout(null), the application doesn't show my modifications. If don't use this command, the modification are loaded.
    I don't know what happes with this layout. Is it a problem of layout or a problem of JPanel references?
              canvas = new AVLTreeAnimation();
              //canvas.setLayout(null);
              JLabel label = new JLabel("trestadf");
              label.setLocation(10, 10);          
              canvas.add(label);
              canvas.setBorder(new TitledBorder(null,"AVL-Tree Animation",
                        TitledBorder.LEFT, TitledBorder.TOP));
              canvas.repaint();          
              return canvas;thanks for your help

    man, this same problem's come up a lot this week.
    If you set the layout to null, you have to set the size and the location, not just the location. All components have a size of 0 x 0 initially.

  • Java bug in a multi monitor application

    Hi,
    I am developing an application using three monitors on windows platform. I am using a NVidia GeForce 4 card to derive the monitors. My application opens up in a secondary monitor, It consists of a Canvas whose parent is a JScrollPane, a JTree whose parent is another JScrollPane. The problem is if I load an image on the canvas and slide the scrollbars attached to the canvas, The canvas does not repaint itself, for which I had to add a listener which repaints the canvas each time the scrollbars are slided. Similar problem is with the JTree scroller, so I call the UpdateUI for the jtree each time the scroller is slided. A few days ago I added a JCombobox to my application. When i click it, obviously a dropdown menu appears with a slider. When i move the slider, the JComboBox does not repaint and I am having difficulty capturing the combobox's slider event. That's not all, I also experienced the repaint problem with other swing components for which I have to explicitly call the UpdateUI method. I got to a point that I had to literally call the update method for every swing component I am using which is dropping my applications efficiency. So I changed my monitor's setting and assigned my secondary monitor as the primary monitor using the windows display properties and it worked. The scrollbars work, and everything is repainting. So the solution is to change my display setting programatically so that the secondary monitors becomes the primary monitor, but I am not able to do that. I need some help regarding this.
    If I have three monitors on a single computer, and I want to change the secondary monitor to primary, how can I do it using Java?
    I hope I explained the problem. I hope someone has an answer.
    Babar Noor

    Using Java:
    java version "1.5.0_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_02-b09)
    Java HotSpot(TM) Client VM (build 1.5.0_02-b09, mixed mode)
    When working in a multiscreen environment using NVIDIA Quadro PCI-E Series' Quadro NVS 280 PCI-E, with two screens (1024x768 display) , DirectX 9.0. One screen is oriented as portrait (secundary screen), the other a landscape (primary screen).
    I run my Swing application, move the frame to the portrait oriented screen,
    The gui has a default JScrollPane, then when I maximize the gui, I get a horizontal and vertical scrollbar. Moving the horizontal scrollbar , the default viewport fails to repaint the screen correctly.
    The solution that worked for me was to set the ViewPort's scrollMode:
    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
    as suggested in
    http://forum.java.sun.com/thread.jspa?messageID=3625667&#3625667

Maybe you are looking for

  • [SOLVED] Pacman trying to install 64-bit packages on 32-bit system

    I was upgrading my Arch Linux i686 install, and I got the following error: error: The mirror 'http://mirror.rit.edu/archlinux/$repo/os/$arch' contains the $arch variable, but no Architecture is defined. I added Architecture = i686 to /etc/pacman.conf

  • Error when loading security file .sec

    Hi I am getting error when tried to load security file Below  is extract of security file !FILE_FORMAT=2.0 !VERSION=11.12 !USERS_AND_GROUPS Praveen@Native Directory admin@Native Directory !SECURITY_CLASSES [Default] 123 !ROLE_ACCESS Provisioning Mana

  • Booting up a windows install

    I tried to install windows 7 with boot camp but got no luck. I get asked to press any key but no key will work! Tried an aly keyboard and also normal windows keyboard. Neither of them seem to work at the caps lock light deosnt come on. So, I installe

  • Deployment Steps

    Dear Colleague, I am new to the OWB world. We are almost done with the development of our first solution. I will have to deploy our solution at our customer. Are you aware of a document that describes the steps for deployment? My current understandin

  • NO SERVICE keeps popping up

    yo i just got a new sim card cuz i got a new data plan and it be acting up son. everytime i put it in i get "no signal." i tried resetting the network, adjusting the sim card, and turnin the phone off, puttin the sim in, turnin it on, all that stuff.