Draw polygon in applet

HI,
I want to be able to draw polygon using java applet. I have code to draw poly in an applet but I am wondering if the java tool can draw directly on html image not on image inside of applet.
Please help
Ying

You can generate a gif which is displayed inside a HTML screen.
Note: HTML does not support polygon drawing so you cannot write HTML to draw a polygon. Unless you want a rectangle (use a table :)

Similar Messages

  • Draw polygon using iText

    hi...
    i am working on projects that create some pdf files.. and am using iText to create the pdf files..
    i am trying to draw a polygon(size-5) ..but i cant find anything in itext that help me
    to create that polygon,,,,
    so tell me some way or any tutorials ?
    Thanks & Regards
    fun_with_me

    fun_with_me wrote:
    >
    Oh dear!
    And we are still waiting for you to learn [How to Ask Questions the Smart Way|http://www.catb.org/~esr/faqs/smart-questions.html] .
    if you dont have the answer ..just leave it..
    before suggesting others...
    i think you need to check your manner first.If you had followed the link, you would have seen that the first rule under "When You Ask" is "Choose your forum carefully" and includes the following advice:
    Be sensitive in choosing where you ask your question. You are likely to be ignored, or written off as a loser, if you:
    post your question to a forum where it's off topic
    The first step, therefore, is to find the right forum. Again, Google and other Web-searching methods are your friend. Use them to find the project webpage most closely associated with the hardware or software giving you difficulties. Usually it will have links to a FAQ (Frequently Asked Questions) list, and to project mailing lists and their archives. These mailing lists are the final places to go for help, if your own efforts (including reading those FAQs you found) do not find you a solution. The project page may also describe a bug-reporting procedure, or have a link to one; if so, follow it.Clearly you didn't read the link before writing it off as, um, whatever you wrote it off as. I'd recommend reading the manual before posting again.

  • Help with the Drawing in an applet!!!!

    I've made the following code.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    <applet code ='Scribble.java' width=300 height =300>
    </applet>
    public class Scribble extends Applet
    implements MouseListener,ActionListener, MouseMotionListener,ItemListener
    Choice shape;
    String msg="";
    int last_x = 0;
    int last_y = 0;
    int clickx=0,clicky=0;
    public void init()
    shape = new Choice();
    shape.add("Line");
    shape.add("FreeHand");
    shape.select("FreeHand");
    shape.addItemListener(this);
    add(shape);
    Button clear = new Button("clear");
    add(clear);
    addMouseListener(this);
    addMouseMotionListener(this);
    clear.addActionListener(this);
    public void paint(Graphics g)
    g.drawString(msg,30,40);
        public void mousePressed(MouseEvent me)
         last_x=me.getX();
         last_y=me.getY();
         clickx=me.getX();
         clicky=me.getY();
         public void mouseEntered(MouseEvent me)
         public void mouseExited(MouseEvent me)
         public void mouseReleased(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseMoved(MouseEvent me)
         public void mouseDragged(MouseEvent me)
         //For drawing Freehand
         if(shape.getSelectedItem().equals("FreeHand"))
         Graphics g = getGraphics();
         g.drawLine(last_x,last_y,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
         //For Drawing Line
         if(shape.getSelectedItem().equals("Line"))
         Graphics g = getGraphics();
         g.setColor(Color.white);
         g.drawLine(clickx,clicky,last_x,last_y);
         g.setColor(Color.red);
            g.drawLine(clickx,clicky,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
              /*For Button*/
         public void actionPerformed(ActionEvent ae)
         String str=ae.getActionCommand();
         if(str.equals("clear"))
         repaint();
         public void itemStateChanged(ItemEvent ie)
    }Now my problem is that the thing which I've used for drawing the line...I have erased the previous position of the line by drawing it in WHITE color. But the problem is that if the line was drawn over the existing line then the line which was there before gets erased as the pixel positions are turned to WHITE color. Please help me with this as I want to give the user and idea as to where the line is being drawn like in MS paint.

    I've made the following code.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    <applet code ='Scribble.java' width=300 height =300>
    </applet>
    public class Scribble extends Applet
    implements MouseListener,ActionListener, MouseMotionListener,ItemListener
    Choice shape;
    String msg="";
    int last_x = 0;
    int last_y = 0;
    int clickx=0,clicky=0;
    public void init()
    shape = new Choice();
    shape.add("Line");
    shape.add("FreeHand");
    shape.select("FreeHand");
    shape.addItemListener(this);
    add(shape);
    Button clear = new Button("clear");
    add(clear);
    addMouseListener(this);
    addMouseMotionListener(this);
    clear.addActionListener(this);
    public void paint(Graphics g)
    g.drawString(msg,30,40);
        public void mousePressed(MouseEvent me)
         last_x=me.getX();
         last_y=me.getY();
         clickx=me.getX();
         clicky=me.getY();
         public void mouseEntered(MouseEvent me)
         public void mouseExited(MouseEvent me)
         public void mouseReleased(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseMoved(MouseEvent me)
         public void mouseDragged(MouseEvent me)
         //For drawing Freehand
         if(shape.getSelectedItem().equals("FreeHand"))
         Graphics g = getGraphics();
         g.drawLine(last_x,last_y,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
         //For Drawing Line
         if(shape.getSelectedItem().equals("Line"))
         Graphics g = getGraphics();
         g.setColor(Color.white);
         g.drawLine(clickx,clicky,last_x,last_y);
         g.setColor(Color.red);
            g.drawLine(clickx,clicky,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
              /*For Button*/
         public void actionPerformed(ActionEvent ae)
         String str=ae.getActionCommand();
         if(str.equals("clear"))
         repaint();
         public void itemStateChanged(ItemEvent ie)
    }Now my problem is that the thing which I've used for drawing the line...I have erased the previous position of the line by drawing it in WHITE color. But the problem is that if the line was drawn over the existing line then the line which was there before gets erased as the pixel positions are turned to WHITE color. Please help me with this as I want to give the user and idea as to where the line is being drawn like in MS paint.

  • Drawing rectangles in Applet

    Hi all.
    I am looking to manipulate this code so that the user can draw rectangles rather than dragging dots to the screen.
    any ideas how I would do this?
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class L10DragMouse extends Applet {
         private int xValue = -10, yValue = -10;
         public void init()
              addMouseMotionListener(new MotionHandler(this) );
         public void paint( Graphics g )
              g.drawString("Drag the mouse to draw", 10, 20);
              g.fillOval(xValue, yValue, 4, 4);
         public void update(Graphics g) {paint(g); }
         public void setCoordinates(int x, int y)
              xValue = x;
              yValue = y;
              repaint();
    class MotionHandler extends MouseMotionAdapter {
         private L10DragMouse dragger;
         public MotionHandler(L10DragMouse d) {dragger = d;}
         public void mouseDragged( MouseEvent e )
              { dragger.setCoordinates(e.getX(), e.getY() ); }
    }

    Okay it is compiling for me now but is not allowing me to create rectangles when the applet opens up. Just a plain page and no graph / rectangle when I drag mouse.
    any ideas?
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class L10DragMouse extends Applet {
         private int xValue = -10, yValue = -10;
            private int origX = -10, origY = -10;
         public void init()
              addMouseMotionListener(new MotionHandler(this) );
         public void paint( Graphics g )
              g.drawString("Drag the mouse to draw", 10, 20);
              g.fillRect(xValue, yValue, origX, origY);
         public void update(Graphics g) {paint(g); }
         public void setCoordinates(int x, int y)
              xValue = x;
              yValue = y;
              repaint();
            public void setOriginalCoordinates(int x, int y)
                origX = -10;
                origY = -10;
    class MotionHandler extends MouseMotionAdapter {
         private L10DragMouse dragger;
         public MotionHandler(L10DragMouse d) {dragger = d;}
         public void mouseDragged( MouseEvent e )
              { dragger.setCoordinates(e.getX(), e.getY() ); }
            public void mousePressed( MouseEvent e )
                    { dragger.setOriginalCoordinates(e.getX(), e.getY() );}
    }

  • Newbie question - Drawing objects in applet

    Hi,
    I'm pretty new to java, and I have a small problem involving drawing a rectangle on a java applet.Firstly this is not a plea for someone to help me with this peice of work, I just need pointing in the right direction.
    Ok the problem.
    I am creating a program that ask the user to input a height value, the program will then do a calculation and create a golden ratio width. The type of both the height and the width are double.
    This is where the problem starts. The next thing I need to do is make the program draw the rectangle using the user inputted height and the calculated width.
    I have a feeling that the problem has occured because I haven't converted the type double into a int type.
    Here is my code
    import java.awt.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    * Class Test - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            String firstNumber;
            double sum1;
            firstNumber = JOptionPane.showInputDialog("Please enter the height" );
            number1 = Double.parseDouble( firstNumber );
            sum1 = (Math.sqrt(5) + 1) / 2;
            sum = number1 * sum1;
            int height = (int)number1;
            int width = (int)sum;
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            // provide any initialisation necessary for your JApplet
         * Called by the browser or applet viewer to inform this JApplet that it
         * should start its execution. It is called after the init method and
         * each time the JApplet is revisited in a Web page.
        public void start()
            // provide any code requred to run each time
            // web page is visited
         * Called by the browser or applet viewer to inform this JApplet that
         * it should stop its execution. It is called when the Web page that
         * contains this JApplet has been replaced by another page, and also
         * just before the JApplet is to be destroyed.
        public void stop()
            // provide any code that needs to be run when page
            // is replaced by another page or before JApplet is destroyed
         * Paint method for applet.
         * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // simple text displayed on applet
            g.drawRect( 15, 10, 270, 20 );
            g.drawString("The sum is " + number1, 25, 25 );
            g.drawRect( 100, 100, height, width);
         * Called by the browser or applet viewer to inform this JApplet that it
         * is being reclaimed and that it should destroy any resources that it
         * has allocated. The stop method will always be called before destroy.
        public void destroy()
            // provide code to be run when JApplet is about to be destroyed.
         * Returns information about this applet.
         * An applet should override this method to return a String containing
         * information about the author, version, and copyright of the JApplet.
         * @return a String representation of information about this JApplet
        public String getAppletInfo()
            // provide information about the applet
            return "Title:   \nAuthor:   \nA simple applet example description. ";
         * Returns parameter information about this JApplet.
         * Returns information about the parameters than are understood by this JApplet.
         * An applet should override this method to return an array of Strings
         * describing these parameters.
         * Each element of the array should be a set of three Strings containing
         * the name, the type, and a description.
         * @return a String[] representation of parameter information about this JApplet
        public String[][] getParameterInfo()
            // provide parameter information about the applet
            String paramInfo[][] = {
                     {"firstParameter",    "1-10",    "description of first parameter"},
                     {"status", "boolean", "description of second parameter"},
                     {"images",   "url",     "description of third parameter"}
            return paramInfo;
    }Thanks for any suggestions.

    Hey ProjectMoon, I had to re-register because it wouldn't let me log back in for some reason.Anyway thanks for the information, i'm trying to get my head around what you said, also I tried printing the height in the drawstring,and as you predicted I got a value of 0. I just wanted to know wjat you mean by:
    "You want to store your height and width in the instance variables you have declared."
    Because I thought I had declared them at the top of the page
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;One further question, is the method I used to convert double to int correct?
    int height = (int)number1;
    int width = (int)sum;Thanks again for the time you have spend answering the questions.

  • Drawing triangles in Applet

    hi Friends,
    I need to draw some triangles in sequence in an applet.I have drawn two triangles to start with,the code for which is:
    public class triangle extends Applet {
      public void paint (Graphics g)
        g.drawLine(50,50,25,100);
        g.drawLine(25,100,75,100);
        g.drawLine(50,50,75,100);
        g.drawLine(100,50,125,100);
        g.drawLine(75,100,100,50);
        g.drawLine(75,100,125,100);
    }But,I dont think this is the right way .. can you please tell me how can i use a method where I can send the 3 points and it returns me with a triangle and in the end i merge all those triangles.Please help me guys.
    Thanks
    Mick

    java.awt.Polygon

  • Java.lang.StackOverflowError problem, drawing images in applet :(

         * Paints the applet
        @Override
        public void paint(Graphics g)
            if(running && levelOne)
            g.setColor(Color.MAGENTA);
            g.drawString("HP Left: " + player.getHP(), 100, 10);
    //      g.drawString("Time Left: " + timer.getTime(), 170, 10);
            g.drawString("Score: " + player.getScore(), 30, 10);
            g.drawString("Required Score To Next Level: " + player.getScore() + "/3000", 100, 190);
            g.drawString("Level: 1", 30, 190);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
            if(start && storyStarted)
                try
                    update(g);
                    paintStory();
                catch(java.lang.StackOverflowError sofe)
                    System.exit(0);
            else if(start)
                g.drawImage(image, 0, 0, this);
                g.drawImage(gun, 200, 400, this);
         * Updates the paint() method and the applet
        @Override
        public void update(Graphics g)
            if(dbImage == null)
                dbImage = createImage(this.getWidth(), this.getHeight());
                dbG = dbImage.getGraphics();
            dbG.setColor(getBackground());
            dbG.fillRect(0, 0, this.getWidth(), this.getHeight());
            dbG.setColor(getForeground());
            paint(dbG);
            g.drawImage(dbImage, 0, 0, this);
        public void paintStory()
            getGraphics().drawImage(story1, 0, 0, this);
        }I know that my problem appears somewhere in the above written code, so if you would take a look, and try to help me fixing my problem! :D

    Vimsie wrote:
    I get a StackOverflowError, but the image isn't flickering!Err, the image is not flickering because there are no repaints happening anymore due to the StackOverflowError. This is hardly an argument for your approach.
    However, I have to admit I don't know how to solve your flickering problem. I've never used AWT but always SWING (but then I don't do applets).
    Maybe google can help?

  • Drawing in Applet ??? Please help

    Hi
    Im trying to create a class Component that draws in
    a applet without passing the applet Graphics into the
    class Component.
    I have read same posts but didnt find nothing, only
    public void paint(Graphics g) {
    super.paint(g);
    or
    classComponent.paint(g);
    There most be a way of drawing in the applets without doing
    this, like the Buttons (and more) only do -
    Button b = new Button("MyButton");
    b.setBounds(10,10,100,100);
    this.add(b);
    and the button is draw in the applet without passing
    the applet Graphics.
    Please help.
    Thanks

    When the applet is painted, it paints each of the Components that you have added by calling the components paint() method and passing the component a Graphics. You need a Graphics if you want to do your own drawing.

  • Drawing from Component into Applet ???

    Hi
    I would like to know if is there any way of drawing into a applet
    from a component without passing the applet Graphics into the
    component and without using the component paint(Graphics g),
    and if yes please help.
    Thanks

    use the tag param namelike that:
    <html><head><title>the title</title></head><body>
       <applet code=?? width=200 height=100>
          <param name=image value=BBB.gif>
       </applet>
    </body></html>and then, in your applet code, your retrieve the image file using the following commands:
    URL address = getDocumentBase();
    String filename = getParameters("image");
    Image picture = getImage(filename);

  • Looking for a 2D Polygon Bevel Algorithm

    I am looking for a graphics algorithm to give two-dimensional polygons a 3D beveled edge look. The polygon should look like as though it is lit from the top-left. This is trivial for rectangular figures, but obviously much more complex for general polygons. The algorithm needs to support any type of polygon, including those with splines or other curved edges, as well as convex figures. Making matters even more complicated, it must also handle texture-filled polygons.
    A Java class that provides this functionality would be perfect. Short of that, an implementation in any language, or even a description of an algorithm, would be helpful.
    I created a java applet to illustrate the problem I am trying to solve - see the source below. This applet with source is also available at
    http://www.keithhilen.com/Java/bevel/
    Keith Hilen
    [email protected]
    Polygons.java :
    import java.applet.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    public class Polygons extends Applet
    Image image;
    int polyWidth = 100;
    int polyHeight = polyWidth;
    int polyOfsX1 = 100;
    int polyOfsY1 = 100;
    int polyOfsX2 = 250;
    int polyOfsY2 = 100;
    int polyOfsX3 = 100;
    int polyOfsY3 = 240;
    int polyOfsX4 = 250;
    int polyOfsY4 = 240;
    Polygon octagon;
    Ellipse2D.Double ellipse;
    GeneralPath ornament;
    BufferedImage imageBuf1, imageBuf2, imageBuf3, imageBuf4;
    public void init()
    image = loadImage("background.jpg");
    createPolygons();
    createImageBufs();
    private Image loadImage(String name)
    MediaTracker tracker = new MediaTracker(this);
    Image image = getImage(getDocumentBase(), name);
    tracker.addImage(image, 0);
    for ( ; ; )
    try { tracker.waitForAll(); } catch (InterruptedException e) { }
    if (tracker.checkAll())
    break;
    return image;
    public void createPolygons()
    double sqrt2 = Math.sqrt(2);
    int m1 = (int) (polyWidth / (2 + sqrt2));
    int m2 = (int) (polyWidth * sqrt2 / (2 + sqrt2));
    octagon = new Polygon();
    octagon.addPoint(-m2/2, -(m1 + m2/2));
    octagon.addPoint(+m2/2, -(m1 + m2/2));
    octagon.addPoint(+(m1 + m2/2), -(m2/2));
    octagon.addPoint(+(m1 + m2/2), +(m2/2));
    octagon.addPoint(+m2/2, +(m1 + m2/2));
    octagon.addPoint(-m2/2, +(m1 + m2/2));
    octagon.addPoint(-(m1 + m2/2), +(m2/2));
    octagon.addPoint(-(m1 + m2/2), -(m2/2));
    ellipse = new Ellipse2D.Double(-polyWidth/2, -polyWidth/2, polyWidth, polyWidth*3/4);
    ornament = new GeneralPath();
    int l = polyWidth/2;
    int m = polyWidth/16;
    int s = polyWidth/32;
    ornament.moveTo(+0+0, -l+0);
    ornament.quadTo(+0+s, -l+0, +0+s, -l+s);
    ornament.quadTo(+m+0, -m+0, l-s, 0-s);
    ornament.quadTo(+l+0, +0-s, l0, +0+0);
    ornament.quadTo(+l+0, +0+s, l-s, 0+s);
    ornament.quadTo(+m+0, m0, +0+s, +l-s);
    ornament.quadTo(+0+s, l-0, 0+0, l0);
    ornament.quadTo(+0-s, l0, +0-s, +l-s);
    ornament.quadTo(-m+0, m0, -l+s, +0+s);
    ornament.quadTo(-l+0, +0+s, -l+0, +0+0);
    ornament.quadTo(-l+0, +0-s, -l+s, +0-s);
    ornament.quadTo(-m+0, -m+0, +0-s, -l+s);
    ornament.quadTo(+0-s, -l+0, -0+0, -l+0);
    public void createImageBufs()
    Graphics2D g2d;
    Composite saveAlpha;
    // Figure 1
    // Create image buf and get context
    imageBuf1 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf1.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR,
    0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(octagon);
    g2d.setColor(Color.blue);
    g2d.fillRect(-polyWidth/2, -polyHeight/2, polyWidth, polyHeight);
    // Figure 2
    // Create image buf and get context
    imageBuf2 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf2.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR,
    0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(octagon);
    g2d.drawImage(image, -polyWidth/2, -polyWidth/2, null);
    // Figure 3
    // Create image buf and get context
    imageBuf3 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf3.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(ellipse);
    g2d.drawImage(image, -polyWidth/2, -polyWidth*5/8, null);
    // Figure 4
    // Create image buf and get context
    imageBuf4 = new BufferedImage(polyWidth, polyHeight, BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf4.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(ornament);
    g2d.drawImage(image, -polyWidth/2, -polyWidth/2, null);
    public void paint(Graphics g)
    g.drawImage(imageBuf1, polyOfsX1 - polyWidth/2, polyOfsY1 - polyHeight/2, null);
    g.drawImage(imageBuf2, polyOfsX2 - polyWidth/2, polyOfsY2 - polyHeight/2, null);
    g.drawImage(imageBuf3, polyOfsX3 - polyWidth/2, polyOfsY3 - polyHeight/2, null);
    g.drawImage(imageBuf4, polyOfsX4 - polyWidth/2, polyOfsY4 - polyHeight/2, null);
    Polygons.html :
    <applet
    code=Polygons.class
    name=Polygons
    width=360
    height=300>
    </applet>

    Think you'll be lucky to find anything in the forum on push down automata. Do a search on google, perhaps with the keyword "parser" or "grammer checker" thrown in. There may well be whole books devoted to it!

  • Drawing help!!!

    Hi everyone,
    I just needed help with my java drawing program. I have to create a program that will allow user input to choose the demo they want. For example, demo1 will be "draw lines", demo 2 will be "draw oval" and so on.. However, my main problem is, how will i draw 10 lines?? would i use a loop? This is what i have so far and it's been driving me nuts because it only draws one line... i'd like it to offset by 1... but it doesn't seem possible no matter what i do. Also there's a circledemo in there where it requires me to use drawOval to draw the circles and have them in a pattern... the third demo wants me to color them. and the last demo which is a rectangle demo wants me to place any rectangle randomly on the applet... This is what i have so far.
    import javax.swing.JOptionPane;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    * @author
    * @version
    public class Shapes2 extends JApplet
    String input;
    int choice;
    int lines=10;
    public void init()
    do
    input = JOptionPane.showInputDialog("Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" +
    "Enter 3 to draw ovals\n" + "Enter 4 to draw polygons");
    choice = Integer.parseInt(input);
    //paint(Graphics g);
    repaint();
    }while (choice > 4);
    public void paint(Graphics g)
    switch (choice)
    case 1:
    if (choice == 1)
    {lineDemo(g);
    break;}
    case 2:
    if (choice == 2)
    {circleDemo(g);
    break;}
    case 3:
    if (choice == 3)
    {circleDemo2(g);
    break;}
    case 4:
    if (choice == 4)
    {rectDemo(g);
    break;}
    default: break;
    } g.drawString("Please enter 1, 2, 3 or 4", 20, 20);
    private void lineDemo(Graphics g)
    g.drawLine(20,20,280,280); // how do i draw 10 lines here???
    private void circleDemo(Graphics g) // draw circles all over the screen ...using nested for loops
    private void circleDemo2(Graphics g) //color the drawn circles from above
    private void rectDemo(Graphics g) // draw any graphical item on the screen randomly
    Edited by: blackcoda786 on May 23, 2009 9:41 PM
    Edited by: blackcoda786 on May 23, 2009 9:43 PM

    import javax.swing.JOptionPane;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    * create a shape then have it repeat 100x.
    * @author
    * @version
    public class Shapes2 extends JApplet
        String input;
        int choice;
        int lines=10;
        public void init()
            do
                input = JOptionPane.showInputDialog("Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" +
                                      "Enter 3 to draw ovals\n" + "Enter 4 to draw polygons"); 
                choice = Integer.parseInt(input);
                //paint(Graphics g);
                repaint();
            }while (choice > 4); 
    public void paint(Graphics g)
                    switch (choice)
                        case 1:
                            if (choice == 1)
                                    {lineDemo(g);
                                    break;}
                        case 2:
                            if (choice == 2)
                                    {circleDemo(g);
                                    break;}
                        case 3:   
                            if (choice == 3)
                                    {circleDemo2(g);
                                    break;}
                        case 4:
                            if (choice == 4)
                                    {rectDemo(g);
                                    break;}
                            default: break;
                    }       g.drawString("Please enter 1, 2, 3 or 4", 20, 20);
               private void lineDemo(Graphics g)
                   // how do i draw 10 lines here???
                    for(int i=0; i<10; i++)
                     g.drawLine(20,20,280,280)
                private void circleDemo(Graphics g) // draw circles all over the screen ...using nested for loops
                private void circleDemo2(Graphics g) //color the drawn circles from above
                private void rectDemo(Graphics g)  // draw any graphical item on the screen randomly
            }Hi cotton, thanks for your reply, i know how to write a for loop, however im not sure if what i did above is correct... it seems to only create 1 line each time...

  • How do I convert this Applet to launch from a JFrame instead??

       A simple program where the user can sketch curves and shapes in a
       variety of colors on a variety of background colors.  The user selects
       a drawing color form a pop-up menu at the top of the
       applet.  If the user clicks "Set Background", the background
       color is set to the current drawing color and the drawing
       area is filled with that color.  If the user clicks "Clear",
       the drawing area is just filled with the current background color.
       The user selects the shape to draw from another pop-up menu at the
       top of the applet.  The user can draw free-hand curves, straight
       lines, and one of six different types of shapes.
       The user's drawing is saved in an off-screen image, which is
       used to refresh the screen when repainting.  The picture is
       lost if the applet changes size, however.
       This file defines two classes, SimplePaint3,class, and
       class, SimplePaint3$Display.class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SimplePaint3 extends JApplet {
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
       public Insets getInsets() {
              // Specify how wide a border to leave around the edges of the applet.
          return new Insets(3,3,3,3);
       private class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display
    } // end class SimplePaint3

    Im quite the novice, how exactly do I go about doing that. What I did was to put both in diff files but I got errors saying that they cant find colorChoice, figureChoice in the Display class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Simple extends JFrame implements Display{
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
    } // end class SimplePaint3
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display

  • Problem with drawing in a scrollpane using clipbounds

    Hello
    Setup is a JFrame containing a splitpane with on the left just some config buttons and on the right a scrollpane.
    Inside the scrollpane I want to draw big waveforms.
    This is represented by a long array of 1's and 0's for the Y coordinates.
    On drawing in paintComponents method I allways reconstruct a GeneralPath, based on the Clipbouns returned by the Graphics variable.
    I have to reconstruct the GeneralPath polygon because my data can be millions long. And therefor I have to limit the points that are drawn.
    When I allways reconstruct this GeneralPath, upon scrolling the polygon is shown scrappy, as in the line connecting the points will only be half shown or almost not.
    Resizing the window or just minimize maximize and it is shown ok.
    I do not have this problem when the GeneralPath I construct is only once made upfront and never remade in the paintComponent method.
    But as I need the clipbounds to know which part to construct I need to rebuild this polygon over and over again.
    I have tried to draw it with Line2D.Double but I get almost the same effect, parts of the lines not being drawn ok.
    Below is the code of the Panel inside the ScrollPane responsible for this drawing.
    public class Usr_Test_L extends JPanel
      final static Color bg   = Color.black;
      final static Color fg   = Color.white;
      final static Color wave = Color.red;
      final static Color txt  = Color.green;
      final static Color grid = Color.lightGray;
      private static final BasicStroke SOLID = new BasicStroke(1.0f);
      private static final BasicStroke BOLD  = new BasicStroke(3.0f);
      private double maxX = 0.0;
      private double maxY = 0.0;
      private double gridWidth;
      private double gridHeight;
      private int panelWidth;
      private int panelHeight;
      boolean firstTime = true;
      private double[] xPoints = null;
      private double[] yPoints = null;
      GeneralPath polygon;
      boolean polyOk = false;
      private double waveHeight = 0;
      private boolean gridOn = true;
      private Usr_Test_R scrollPane = null;
      Usr_Test_L(Usr_Test_R scrollPane)
        super(true);
        this.scrollPane = scrollPane;
        buildGui();
      void buildGui()
        setBackground(bg);
        setForeground(fg);
        //Let the user scroll by dragging to outside the window.
        setAutoscrolls(true); //enable synthetic drag events
    //    addMouseMotionListener(this); //handle mouse drags
        repaint();
      private void generateWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        Random r = new Random();
        for ( int i = 0; i < cycles; i++ )
          xPoints[i] = i;
          yPoints[i] = (int)( Math.pow(-1.0,i) ) * ( r.nextInt(2) );
    //      if ( ( i % 10 ) == 0 ) yPoints[i] = height;
    //      else                   yPoints[i] = height + gridHeight;
    //      System.err.println("P"+i+"("+xPoints[i]+","+yPoints[i]+")");
      private void generateSineWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        double j, xval, yval;
        j = 0;
        int i = 0;
        while (i < cycles)
          xval = j;
          yval = Math.sin(j) * 10.0 + 20;
          xPoints[i] = xval;
          yPoints[i] = yval;
          i++;
          j += 0.01;
      public Dimension getPreferredSize()  // <== used because of revalidate, parent scrollpane asks preferredsize ..., so we overruled the method
        return new Dimension(panelWidth, panelHeight);
      public void drawLine(int cycles, int height)
        generateWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void drawSine(int cycles, int height)
        generateSineWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void zoomIn()
        gridWidth  *= 2;
        gridHeight *= 2;
        repaint();
      public void zoomOut()
        gridWidth  /= 2;
        gridHeight /= 2;
        repaint();
      private void initPanel()
        Dimension d = getSize();
        panelWidth = d.width;
        panelHeight = d.height;
        maxX = panelWidth;
        maxY = panelHeight;
        gridWidth  = panelWidth / 8;
        gridHeight = panelHeight / 8;
        scrollPane.getHorBar().setUnitIncrement((int)(gridWidth*3));           // times 2 otherwise no clipbounds are allways too small
        scrollPane.getHorBar().setBlockIncrement((int)(gridWidth*3));
        scrollPane.getVerBar().setUnitIncrement((int)(gridHeight*3));
        scrollPane.getVerBar().setBlockIncrement((int)(gridHeight*3));
      public void grid()
        if ( gridOn ) gridOn = false;
        else          gridOn = true;
      private void drawGrid(Graphics2D g2, Rectangle clip)
        if ( ! gridOn ) return;
        // draw grid
        g2.setPaint(grid);
        // new good grid
        double startX = clip.getX() + ( gridWidth - ( clip.getX() % gridWidth ) );
        double endX   = clip.getX() + clip.getWidth();
        double startY = clip.getY() + ( gridHeight - ( clip.getY() % gridHeight ) );
        double endY   = clip.getY() + clip.getHeight();
        double y = startY;
        while ( startX < endX )
          while ( y < endY )
            g2.draw(new Rectangle2D.Double( startX - 0.5, y - 0.5, 1.0, 1.0 ));
            y += gridHeight;
          y = startY;
          startX += gridWidth;
      private boolean buildPolygon(Rectangle clip)
        if ( xPoints != null && yPoints != null )
          polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,xPoints.length);
        else
          return false;
        double x = xPoints[0] * gridWidth;
        double y = waveHeight;
        polygon.moveTo((float)xPoints[0], (float)yPoints[0]);
        for ( int index = 0; index < xPoints.length; index++ )
          x = xPoints[index] * gridWidth;
          y = waveHeight + ( yPoints[index] * gridHeight );
          if ( x > ( clip.getX() + clip.getWidth() ) ) break;
          if ( y < clip.getY() || y > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( x < clip.getX() || x > ( clip.getX() + clip.getWidth()  ) ) continue;
          polygon.lineTo((float)x, (float)y);
        return true;
      private boolean drawLines(Graphics2D g2, Rectangle clip)
        if ( xPoints == null || yPoints == null ) return false;
        double x1 = xPoints[0] * gridWidth;
        double y1 = waveHeight;
        double x2, y2;
        boolean cont = false;
        for ( int index = 0; index < xPoints.length; index++ )
          x2 = xPoints[index] * gridWidth;
          y2 = waveHeight + ( yPoints[index] * gridHeight );
          if ( x1 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( x2 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( y2 < clip.getY() || y2 > ( clip.getY() + clip.getHeight() ) )
            cont = true;
          if ( x2 < clip.getX() || x2 > ( clip.getX() + clip.getWidth()  ) )
            cont = true;
          if ( ! cont ) g2.draw(new Line2D.Double(x1,y1,x2,y2));
          x1 = x2;
          y1 = y2;
          cont = false;
        return true;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if ( firstTime )
          initPanel();
          firstTime = false;
        // get clip bounds
        Rectangle clip = new Rectangle();
        clip = g2.getClipBounds(clip);
        // draw grid
        drawGrid(g2,clip);
        // draw waveform
        g2.setPaint(wave);
        g2.setStroke(SOLID);
        if ( buildPolygon(clip) ) g2.draw(polygon);
    //    if ( polyOk ) g2.draw(polygon);
    //    drawLines(g2,clip);
      }

    I have added a standalone testcase for ease.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class Scrolling {
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(new DrawPanel()));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class DrawPanel extends JPanel {
        private GeneralPath polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
        private int[] coords;
        public DrawPanel() {
            setBackground(Color.white);
            buildPolygon();
        private void buildPolygon() {
         coords = new int[2000];
            Random r = new Random();
            int height = 80;
            int gridHeight = 10;
            int gridWidth = 10;
         int j = 0;       
            for (int i=0, dir=-1; i<1000; i++, dir=-dir) {
                coords[j++] = i * gridWidth;
                coords[j++] = height + dir*gridHeight*r.nextInt(2);
        private void drawPolygonClipped(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
           polygon.moveTo(0,80);
           for ( int i = 0; i < 2000; i++ )
          if ( coords[i] > ( clip.getX() + clip.getWidth() ) ) break;
          if ( coords[i+1] < clip.getY() || coords[i+1] > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( coords[i] < clip.getX() || coords[i] > ( clip.getX() + clip.getWidth()  ) ) continue;
                polygon.lineTo(coords[i++],coords);
    private void drawPolygon(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
         polygon.moveTo(0,80);
         for ( int i = 0; i < 2000; i++ )
              polygon.lineTo(coords[i++],coords[i]);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
         Rectangle clip = new Rectangle();
         g.getClipBounds(clip);
         drawPolygonClipped(clip);
         //drawPolygon(clip);
    g2.draw(polygon);
    public Dimension getPreferredSize() {
    return new Dimension(1500,500);

  • How to add a polygon to mapviewer using Javascript API

    Hi,
    I am using JavaScript API for the MapViewer.
    Using redlining tool, my application allows user to draw polygon onto the map.
    I would like to have union, difference and intersect tools. I know the back end logic can be done using using JTS or SDO_Union, SDO_difference, and SDO_intersection. but how do i display the result polygon on the map? Note that I am not going to store the polygon in the database.
    Thanks for any ideas.

    Hi,
    If I understand well you are using Oracle Maps. User do some redlining, then you somehow makes FOI polygons. Then you get the coordinates of the polygons and send them to the back-end where you can use spatial functions and get the coordinates of the new polygon.
    You can store those coordinates in i.e. hidden input field on page (if you use JSF it is very simple) and then use JavaScript to parse them and Oracle Maps API to create new FOI polygon and add it to mapviewer object. One disadvantage of this concept is that reloading of page (submit) is necessary.
    Branislav

  • Applet problem

    Hi all,
    I am developing a web application in which I am drawing hundreds of applets, which will paint according to status, different colors (based on data feed), my problem is with JRE 1.4.04 the applet will change the color and display the string value without any hickup. But if I change the JRE to 1.4.5 or greater, it changes the color, the string may not draw on the applet!
    Second issue is
    Because some times the number applete on a browser may go beyond 500, while scrolling the browser it takes loong time to scroll.
    Can some one tell me what I am doing wrong?\
    Thanks
    Onapping

    Sorry, you have the wrong forum. This forum is focused on the Web Application Framework (JATO) and the Sun Java Studio Enterprise Tools module used to create WAF apps.
    Although someone on this forum maybe able to help, you might have better success on a forum that is focused on applets and Java in general.

Maybe you are looking for