Drawing a 2D polygon

I am quite new to java and learning some java programming by tackling some questions I found on the net. I was trying out to draw a 4 sided polygon which is drawn by joining a sequence of line segments. The last line segment joins the the first line segment to complete the polygon. How do I make the user click at a sequence of points on a canvas and at each click make the program draw a line connecting the new point to the end of the previous line.?

You need to store a list of click points somewhere, and when painting, you have to iterate over that list each time, and draw the lines between the coordinates. Add to the list when a click event occurs.
Always use an abstraction of what you want to paint (data model) so you can paint repeatedly and don't use information, and are later also able to remove some painted things. If you just work with the component, it's like painting on a canvas: you can't remove or change something once it's painted.

Similar Messages

  • Fast polyline drawing like for polygon...

    I need to draw as fast as possible a lot of
    polylines from arrays of points.
    I tried several ways :
    Way 1 ------------
    GeneralPath polylineShape = new GeneralPath(GeneralPath.WIND_EVEN_ODD,1024);
    polylineShape.moveTo(xpts[0],ypts[0]);
    for (int i=1;i<num_pts;i++) {
    polylineShape.lineTo(xpts,ypts[i]);
    ((Graphics2D)g).draw(polylineShape);
    ->>> TOO SLOW
    Way 2 ------------
    g.drawPolyline(xpts, ypts, num_pts);
    ->>> FASTER but not enough
    Way 3 -----------
    Polygon polygonShape = new Polygon();
    polygonShape.xpoints = xpts;
    polygonShape.ypoints = ypts;
    polygonShape.npoints = num_pts;
    ((Graphics2D)g).draw(polygonShape);
    ->>> 30% faster than Way 2 : but it draws a closed
    polygon, not a polyline
    -> How to draw a polyline as fast as way 3 ?
    (I definitely don't want a polygon, but a polyline)

    You could do the method (3), then just draw the last segment as a line in background color...

  • How to draw Overlapping transparent Polygons with different shades of color

    I had been working with the Graphics package for some time now. I want to now draw multiple polygons without using the fill method i.e by shading a transparent color. The overlapping regions should have a thicker density of the colors. I am currently trying out by creating a Buffered image of the polygons. Let me know if there is any other easy approach..................

    This may be a dumb quesiton and if so, I'm sorry, but why doesn't fill work for you?
    I think that you may do well to create and post the smallest program possible that is compilable, runnable, demonstrates your problem, and has no extraneous code not related to the problem, an [SSCCE.|http://sscce.org] Please see the link for details on how to create one of these because trust me, if your SSCCE is compliant with the specs, you'll likely get a very helpful answer from someone here quickly.

  • Adobe Reader drawing without Comment Tools or Method to set "Make Properties Default" without popup

    Hi everyone,
    Spending a few days to find a solution for drawing lines, polylines, polygons, circles, rectangles, etc. It looks like a "dead end" since I want to develop a plugin for Adobe Reader that can draw custom Lines, Polylines, Polygons, ... (objects I can set my styles without using built-in style dialog). I want to use my custom dialog to set styles and do drawing without using Comment Tools. The problem is: when I use AVPageViewDrawingProc callback, I can draw only rectangle, polyline, polygon, no way to draw circle, text, etc.
    Another solution is to use Comment Tools. But when changing between tools I want to apply my styles to the tool (line color, text color, text size, ...), like the way you right click on an annotation and select "Properties", then mark "Make Properties Default" as checked before selecting "OK". I don't want to show the dialog to confuse user when he changes tools. So, is there any API method to help me selecting an annotation and mark this selected annotation to be default styles?
    I still can't find a way to change text size of FreeText realtime.
    Anybody can help me?
    Kind Regards

    If I were building something like this, I would have my plugin create custom annotations.  You can draw whatever you want in the appearance of the annotation.

  • Polygon object

    I have an idea for a map webapp in mind which requires many
    different shaped 2D-polygons to be placed over a (satellite-image)
    map of an area.
    First I started working with SVG, which works very nice in
    windows. The nice thing about SVG is, that you can create a Polygon
    object, and add it to a container. That polygon can fire
    (mouse)events, works with css (:hover), etc. But all browsers I
    tried on Linux have terrible rendering speeds (i guess it's mostly
    a Linux thing, not because of the browser implementation).
    So I decided to check out Flash. I found out the whole Flex
    stuff and already managed to get compiling working in Eclipse.
    Flash/Flex has many nice high level components, but it seems to be
    missing a Polygon object similar to what SVG has. Sure, you can
    draw lines and polygons on the Graphics attribute of a component
    (Canvas). But that's it. No mouse-hover/click/etc events.
    One could use on Canvas object per polygon, and use the
    Canvas object for events listening. But as far as I can tell that
    would also (logically) trigger the events in the Canvas object
    (/bounding box) but outside the polygon.
    The only solution to getting a Polygon object similar to SVG,
    is to write a custom Polygon container (a Canvas object), to which
    I could add multiple Polygon objects myself. For which I would have
    to keep track on all of them, and in the container event handlers
    check over what polygon the pointer is hovering.
    I have been looking for something like this for the past few
    days now, but couldn't find anything so far. And by posting this, I
    actually hope someone will yell at me and proof me wrong. But I
    don't expect that to happen.
    It's really a shame, SVG isn't fast enough. And even though
    Flash has been here for quite a while, something simple as this
    seems to be missing. Even Silverlight seems to have it (but no
    Linux plugin afaik).

    Ah, it took an extra day but I figured it out. All kinds of
    objects (Sprite, [Simple]Button) allow you to simple draw custom
    shapes. And these objects can be set to use a specific Graphics
    shape to specify the 'hit' area (could see that Graphics object as
    a bit mask). Mouse events will only fire from within that area.
    Probably basic stuff for an experienced Flex programmer, but
    it wasn't obvious to me :)
    So I guess I have all it takes to work on my project
    now.

  • IPhone - OpenGL ES - Polygon Offset

    I need to draw lines over polygons and I am using polygon offset as described here.
    http://www.opengl.org/resources/faq/technical/polygonoffset.htm
    It works fine for me on the desktop but it does not seem to work on OpenGL ES on iPhone. Is there a workaround? Does polygon offset even work on iPhone or are the parameters interpreted differently?

    Your best bet is probably to go to the source and check out the documentation of the PowerVR MBX chipsets directly if you want to know what's in hardware. You can also check out the Khronos OGL ES spec for 1.1 but alot of the added functionality comes from extensions and you don't have control over which extensions are being used.
    http://www.imgtec.com/PowerVR/mbx.asp
    http://www.khronos.org/opengles/
    Good luck,
    =Tod

  • Drive-time polygon creation

    Hello,
    I am new to Oracle spatial.
    Has anyone successfully implemented drive-time polygon creation using
    network data models ?
    I am trying to build a drive-time network contains all streets in the United States.
    Thanks,
    Steven

    Hello,
    By "Drive-time polygon" do you mean something like an isochrone? i.e draw me a polygon that shows the area within 20 minutes driving time of location "X"?
    The NDM (Network Data Model) contains a fairly rich Java API but I can't remember off the top of my head if this functionality is supported "out of the box" or not. Check the docs.... There is a "withinCost" function which sounds promising.
    In my opinion you will struggle to load a fully detailed street network for the entire U.S into the NDM and then use the Java API (or PL/SQL API as this is based on the Java API) without problems. The limits to the amount of memory that can be allocated to a Java process effectively limit the size of the network that can be loaded.
    Check out this thread re: the memory problems :
    Re: Network Memory Object (PL/SQL)
    If you can provide a "window" (MBR) to effectively cut down the area of interest then you may be OK.
    If you want (for example) a list of zipcodes within N minutes of an individual zip code you may be better off buying in a pre-built "drive time matrix" which is just a table containing from zip, to zip & drive time and can be very quickly and easily queried....
    Hope this helps,
    Steve

  • MapKit - User initiated drawing

    Hi all,
    I'm investigating MapKit for an upcoming project. I've found quite a few ways to programmatically draw points, lines, polygons, etc. The one thing I'm having trouble finding is how to allow a user to draw a line or polygon by touching the map. My users want to zoom-in on their property and draw a boundary to represent the state of their land at a given time (typically once per year). Is this type of functionality supported by MapKit? Will this type of functionality be part of Apple's new mapping technology in iOS 6?
    Thanks ahead of any advice,
    David

    jdpal wrote:
    Thanks - I posted it on the server forum as well per your suggestion.
    Do you know if browse mode will let the users restore to the volume that was backed up, opposed to their local desktop?
    I'm not sure. you should try and see what happens. it might. also, when you enter TM interface, scroll back in time and select what you want to restore you can click on the "gears" action button in the toolbar and choose 'restore to". this will let you choose where you want to restore this TO. it can be any volume including a network one. although when I just tried it with a network volume it had strange results. i got an error -36 saying that there was some kind of problem restoring and yet it restored just fine.
    I guess either would be an okay solution but ideally they could put the file back where it originally was.

  • At a dead end.  A java student in need of help.

    I've hit a wall.
    The program is supposed to allow the user to draw five different polygons using the polygon class and let the user pick the color for each polygon and move each polygon around the screen once it is filled in. The user clicks to add the points and then double clicks to fill in the polygon. Then the polygon is added to the array. Up to the dragging around the screen the program works fine. When I click on a polygon with the shift down nothing happens and I've spent several hours trying to figure out why.
    I've placed several System.out.println's in the code and I think I've narrowed down the problem. (I hope) I think it might have something to do with the canvas repainting. Because the S.O.P's show that the program is going through and executing that code. It might also have something to the do with my polygon array, but to my knowledge that is setup fine.
    Thanks a bunch if you try to help.
    Brad
    // Full Code Below
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         private JButton reset;
         private Podly polyArray[] = new Podly[5];
         private Podly currentPoly = new Podly();
         private Podly movingPoly = new Podly();
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              count = 0;
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              reset = new JButton("Reset");
              reset.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(reset);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         public static void main(String [] args)
              JFrame main = new poly();
              main.setSize(600, 600);
              main.setVisible(true);
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else if (test instanceof JButton) // Repaints if Reset Button is Pressed
                   repaint();
                   currentPoly.reset();
                   count = 0;
                   overflowed = false;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon // Class adds Color Fuctionality to Polygon class
              Color polyColor;
              void setColor(Color y)
              {polyColor = y;}
              Color getColor()
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   System.out.println("Canvas is called");
                   System.out.println(polyArray);
                   for (int i=0; i>count;i++)
                        System.out.println("Loop is going");
                        Podly y = polyArray;
                        g.setColor(y.getColor());
                        g.fillPolygon(y);
                        System.out.println(y);
                        System.out.println("Loop has filled in polygon"); // Test
                   System.out.println("painting complete");
         class Points extends MouseAdapter
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // Allows user to play again.
                             repaint();
                             currentPoly.reset();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  System.out.println("Gets before Check loop");
                                  for (int r=count-1;r>=0;r--)
                                       System.out.println("Inside For Check Loop");
                                       System.out.println(polyArray[r]);
                                       if (!polyArray[r].contains(x,y))          
                                            System.out.println("Point is found");
                                            movingPoly = polyArray[r];
                                            System.out.println("MovingPoly Defined");
                                            moving = true;
                                            System.out.println("Moving is true"); // test
                                            break;
                             else
                                  currentPoly.setColor(currentColor);
                                  currentPoly.addPoint(x,y);
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  currentPoly.reset();
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true;}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        System.out.println("Gets here");
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();

    Here is the updated code still with the color error I talked about above.
    :) Thanks for all the help everyone.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class poly extends JFrame implements ActionListener
         /* Accessible Variables */
         private JPanel canvas;
         private JPanel mp;
         private JComboBox choice;
         Podly [] polyArray;
         private Podly currentPoly;
         private Podly movingPoly;
         private int count;
         private Color currentColor;
         private Point firstPoint;
         private Color polyColor;
         private boolean newPoly = true;
         private boolean moving = false;
         private boolean overflowed = false;
         poly()
              setTitle("Polygon");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // Exits program on window close.
              polyArray = new Podly[5];
              count = 0;                                      // Set count to zero.
              /* Interactive Buttons and Menus */
              JMenuBar tp = new JMenuBar();
              JMenu color = new JMenu("Color");
              JMenuItem MBlack = new JMenuItem("Black");
              color.add(MBlack);
              JMenuItem MRed = new JMenuItem("Red");
              color.add(MRed);
              JMenuItem MGreen = new JMenuItem("Green");
              color.add(MGreen);
              JMenuItem MYellow = new JMenuItem("Yellow");
              color.add(MYellow);
              MBlack.addActionListener(this);
              MRed.addActionListener(this);
              MGreen.addActionListener(this);
              MYellow.addActionListener(this);
              tp.add(color);
              canvas = new CanvasArt();
              canvas.setBackground(Color.white);
              canvas.addMouseListener(new Points());
              canvas.addMouseMotionListener(new Moved());
              choice = new JComboBox();
              choice.addItem("Black");
              choice.addItem("Red");
              choice.addItem("Green");
              choice.addItem("Yellow");
              choice.addActionListener(this);
              JLabel chooseColor = new JLabel("Choose a color:");
              JLabel holdShift = new JLabel("Hold shift, click, and drag to move a polygon.");
              mp = new JPanel();
              mp.add(chooseColor);
              mp.add(choice);
              mp.add(holdShift);
              setJMenuBar(tp);
              getContentPane().add(canvas);
              getContentPane().add(mp, "South");          
         /* Button Listeners */
         public void actionPerformed(ActionEvent e)
              Object test = e.getSource();
              Object selection;
              if (test instanceof JComboBox)
                   JComboBox source = (JComboBox)e.getSource();
                   selection = source.getSelectedItem();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
              else
                   JMenuItem source = (JMenuItem)e.getSource();
                   selection = source.getText();
                   if (selection.equals("Black")) currentColor = Color.black;
                   else if (selection.equals("Red")) currentColor = Color.red;
                   else if (selection.equals("Green")) currentColor = Color.green;
                   else if (selection.equals("Yellow")) currentColor = Color.yellow;
         class Podly extends Polygon  // Class adds Color Fuctionality to Polygon class
              void setColor(Color y)  // sets the Polygon's color.
              {polyColor = y;}
              Color getColor()   // returns the Polygon's color.
              {return polyColor;}
         /* Canvas Painting Panel */
         class CanvasArt extends JPanel
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                        for (int i=0; i<count;i++)
                             g.setColor(polyArray.getColor());
                             g.fillPolygon(polyArray[i]);
         class Points extends MouseAdapter
              /* Listens for mouse press, constructs polygons, stores them in array. */
              public void mousePressed(MouseEvent e)
                   Graphics g = canvas.getGraphics();
                   if (overflowed) // Checks for overflow in program.
                        g.setColor(Color.RED);
                        Font font = new Font("SansSerif",Font.BOLD, 30);
                        g.setFont(font);
                        g.drawString("OVERFLOW", 10, 30);
                        Font font2 = new Font("SansSerif",Font.BOLD, 20);
                        g.setFont(font2);
                        g.setColor(Color.BLUE);
                        g.drawString("Double Click to Play Again", 10, 50);
                        if (e.getClickCount() == 2) // allows user to play again by resetting.
                             repaint();
                             count = 0;
                             overflowed = false;
                   else
                        int x = e.getX();
                        int y = e.getY();
                        if (newPoly)
                             firstPoint = new Point(x,y);
                             if (e.isShiftDown())
                                  for (int r=count-1;r>=0;r--)
                                       if (polyArray[r].contains(x,y))          
                                            movingPoly = polyArray[r];
                                            moving = true;
                                            break; // exits for loop after Polygon with point is found.
                             else
                                  currentPoly = new Podly();
                                  currentPoly.addPoint(x,y); // Adds the first point.
                                  currentPoly.setColor(currentColor); // Sets the Polygon Color
                                  g.fillOval(x,y,1,1);
                                  newPoly = false;
                        else
                             /* Close the current Polygon at double click,
                             * then moves on to the next. */
                             if (e.getClickCount() == 2)
                                  g.setColor(currentPoly.getColor());
                                  g.fillPolygon(currentPoly);
                                  polyArray[count] = currentPoly;
                                  count++;
                                  if (count == polyArray.length)
                                  {overflowed = true; canvas.repaint();}
                                  newPoly = true;
                             else
                                  g.setColor(currentPoly.getColor());
                                  currentPoly.addPoint(x,y);
                                  g.drawLine(firstPoint.x, firstPoint.y, x, y);
                                  firstPoint.move(x,y);
              /* Listens for mouse release */
              public void mouseReleased(MouseEvent e)
                   if(e.isShiftDown())
                   { moving = false; }
         /* Moves selected Polygon around */
         class Moved extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   if (moving && e.isShiftDown())
                        int x = e.getX();
                        int y = e.getY();
                        movingPoly.translate((x-firstPoint.x),(y-firstPoint.y));
                        firstPoint.move(x,y);
                        canvas.repaint();
         public static void main(String [] args)
              JFrame poly = new poly();
              poly.setSize(600, 600);
              poly.setVisible(true);

  • Am I the only one with the mysterious black box?

    If more than one AA window is open (9.4.2, Win7)  and I try to draw with a polygon or other graphic tool, a black rectangle begins tracking my cursor, obscurring the graphic line I am trying to create. It grows to the scale of the polygon, etc., but disappears as soon as I stop drawing and the shape becomes inactive.  If more than one window has been opened anytime during a session, and I want to draw, I have to close the program and reboot in order to not have the problem. 

    Hi there,
    The good news is that M-Audio have just released a new set of drivers. Check out the following support article:
    http://www.m-audio.com/index.php?do=support.faq&ID=36be2fb74b90752fe3568b07c20a2 189
    While this relates specifically to Leopard, perhaps you were falling foul of some driver issue.
    Time to try updating your existing drivers and let us know. By the way, no, you were FAR from the only person with this problem. M-Audio have been very slow in getting drivers out. Let's hope this is now a thing of the past.
    Pete

  • Creating a texture for a rounded window

    Hi.
    I'm creating a simple gui on a game framework based on lwjgl and I have a problem.
    Almost every window has a solid black texture as a background. I came up with a idea to make corners rounded. At the beginning I created gif picture of a rounded square and used it as a background texture. But it wasn't a good idea, because the corners had different sizes depends on windows sizes (and how much texture was stretched). I've decided that I have to create a texture dynamically every time a window is created.
    public void makeBackground() {
            // the texture size must be multiply of 2
            int tWidth = 2;
            while (tWidth < getWidth()) {
                tWidth *= 2;
            int tHeight = 2;
            while (tHeight < getHeight()) {
                tHeight *= 2;
            Texture t = new Texture(getWidth(), getHeight()); // new texture is created with width and height same as the window size
            int px, py, ox, oy; // some variables
            final int pw = getWidth(),  ph = getHeight(),  hww = tWidth; // as above
            ByteBuffer bb = t.getData(); // blank texture is converted to a byte buffer
            Utils.startStoper(); // start timer (for a benchmark)
            try {
                for (int p = 0;; p++) {
                    px = p % hww; // get the X of the pixel
                    py = p / hww; // get the Y of the pixel
                    ox = ROUND_ANGLE - Math.min(px + 1, pw - px + 1); //  ox = <0, 32> if near corners
                    oy = ROUND_ANGLE - Math.min(py + 1, ph - py + 1); //  as above
                    bb.put((byte) 0); // r = 0
                    bb.put((byte) 0); // g = 0
                    bb.put((byte) 0); // b = 0
                    if (ox > 0 && oy > 0) {  // if near corners
                        double hypot = Math.hypot(ox, oy);
                        if (hypot > ROUND_ANGLE) { // if outside the corner
                            bb.put((byte) 0); // apha = 0
                        } else if (hypot > ROUND_ANGLE - 1) { // if on the corner edge
                            bb.put((byte) Math.round(
                                    (ROUND_ANGLE - hypot) * 200));
                        } else {
                            bb.put((byte) 200);  // if inside the corner (200 is a max value cause the whole window is a bit transparent)
                    } else {
                        bb.put((byte) 200); // inside the window
            } catch (BufferOverflowException ex) {
            Utils.stopStoper();  // stop timer
            t.setData(bb);   // set data for a texture
            super.setImage(t);  // set texture as a background
        }And here we have a problem. The whole method takes about 70ms for a window 200x200.
    I can do it in another way: create a pictures of a rounded corner and a black box. The box would be the window inside and the corner would loaded 4 times each time rotated. Only the box would be stretched then. But I would have to override all methods of a window (setX, setY, setXY, some more).
    Any ideas?
    Thanks.
    Edited by: tom_ex on 2009-02-17 16:58

    Hi Tom,
    I haven't used lwjgl, so hope the following helps:
    1- What does it matter if it takes 70ms. Your windows will be created once. At that point juste create the texture for that window and store it until you destroy the window. The penalty hit is 70ms but only at the initialization.
    2- You are drawing a pixel at a time for everything. Why don't you calculate the area of the corners and only draw the corners a pixel at a time. For the rest, draw some filled polygons.
    3- The java Graphics object has method fill methode that can take any Shape object. Why don't you use that?
    I would use a combination of 3 and 1.
    Hope that helps.
    Ekram
    Edited by: ekram_rashid on Feb 18, 2009 2:21 PM

  • Opengl not working in 10.4.7

    I implemented a cocoa application that renders lines and polygons to an OpenGL view. The application was working great in my MacBook Pro when I was running Tiger 10.4.6. After installing 10.4.7 the application stop drawing lines or polygons in wireframe in the OpenGL view.
    The strange thing is that the application works well in a PowerBook G4 running 10.4.7.
    There is something wrong with the 10.4.7 intel update and OpenGL. I appreciate if somebody from the apple community can help me. I was trying to have this project ready this week, but now with the 10.4.7 update I am just lost.

    More info would help us help you. Is this an app you
    created, perhaps with the developer graphics tools
    like Quartz Composer? If so, have you tried
    recompiling it under 10.4.7? Have you downloaded the
    latest Xcode version?
    If not, can you supply more details?
    thanks for your reply:
    I created the application in XCode 2.3
    The application draws to an NSOpenGLView. I created the view in Interface builder 2.5.4, by first subclassing an NSOpenGLView named TrishearView, and then dragging an NSOpenGLView onto my main window and setting its custom class to be TrishearView. I follow the procedure outlined in Hillegass, Cocoa programming book, 2nd. edition, chapter 29.
    I set the attributes of the TrishearView to be: Renderer : best, Color/Alpha buffer: Default, Depth Buffer: minimum, and Stencil buffer minimum.
    The Initialization methods in my TrishearView.h file are:
    initWithFrame:pixelFormat:
    and
    initWithCoder:
    I checked the program and I figured out that the initWithCoder: method was called when starting the program. This method has the following lines:
    self = [super initWithCoder:c];
    [self prepare];
    return self;
    The prepare method has stuff inherent to the view such as lightning, material model, depth buffer, clear color, perspective calculations, and antialiasing.
    The program was working fine until I installed 10.4.7 in my MacBook Pro. Afte r that most lines, or polygons in wireframe are drawn with the same color as the background. I figured out because I can see some lines when superimposed on a filled polygon.
    The weird thing is that I updated to 10.4.7 in my old PowerBook. I compiled the project in my old PowerBook running 10.4.7 and the application worked fine. All lines, polygons filled or in wireframe display great.
    So the problem is in my MacBook Pro running 10.4.7.
    I have read in several forums that is not a good idea to set the pixel format of the NSOpenGLView in Interface Builder. But, this worked fine in 10.4.6 for both G4 and Intel, and in 10.4.7 for Intel. And it this is so buggy, why is there as an option (a very convenient option for a beginner like me) in Interface Builder?
    Also, if there is a bug in my program, why does the program happen to work in my old PowerBook and not in my new MacBook Pro? This is very weird.
    I can´t figure out what is wrong. This has delayed my work considerably. I was trying to meet a deadline. This is the first time I have problems with an update.
    I will be happy to send you the source code if needed. Thanks for your help
    Nestor Cardozo

  • Calling repaint from other Class file.

    Hi,
    First of all i am pretty new to Java so I hope you understand what I am trying to explain..
    I am trying to create an applet which draws some polygons on the screen. For the drawing of these polygons I have created another class which is located in another package but the same project. I plan to use this second package as some kind of library so that i can simple call 2 or 3 functions in future applets to draw these polygons (which always have the same shape). In the library file i have created a contructor, a draw function and some other functions to change some properties. I also created a function that created a popup window as soon as i click on one of the polygons i have created. In the popup some buttons are available which change the color of the polygon. All this works fine, but the problem i have is the following:
    When i click a button the main class (in package 1) needs to be repainted for the changes to be visable. But the main class can always be a different one. Is it possible to check in the class in the library package, which class from the main package called the class, and execute a repaint() on that class. So i have the following situation:
    Package 1 (Applets):
    package applets;
    class myApplet extends Applet implements .... {
    private Tank tank1 = new Tank(20, 20, 100, 200);
    private Tank tank2 = new Tank(250, 20, 100, 200);
    public void paint(Graphics g) {
    tank1.drawTank(g);
    tank2.drawTank(g);
    public void mouseClicked(MouseEvent e) {
    tank1.openWindow();
    tank2.openWindow();
    Package 2 (Library):
    package applets.library;
    class Tank {
    public Tank(int xPos, int yPos, int height, int width) {
    public void drawTank(Graphics g) {
    public void openWindow() {
    new myWindow("Window1");
    public class myWindow extends Frame {
    public myWindow(String name) {
    show();
    public boolean action(Event e, Object arg) {
    return true;
    So what i want to do is: In class Tank in the public class myWindow in the method action, i want to call the repaint() of the class myApplet
    I hope my problem is clear to you, as you may have noticed i have a little trouble explaining it clearly..

    First of all thanks a lot for your reply and sorry for my way of programming. Like i said i am pretty new to Java, i am actually only programming for about 2 weeks and trying to learn from some examples on the internet.
    I dont really understand what you want me to do, is it maybe possible to give a little bit of sample code? That would help me a lot.
    Maybe some background information about the project will help a bit too.
    I work at a company that develops automation solutions. We program PLC's and SCADA systems. Now Siemens has some PLC's that support Java applets which make it possible to visualize industrial processes. Now i am trying to figure out if it is possible to start developing own java applets for visualisation in the future. Since most programmers here have no experience in any higher programming language i want to keep it as simple as possible, by developing libraries that do the most of the programming work for them.
    Now i want to create the first part of this library by programming some kind of storage tank. This tank always has a valve. when i click on the valve a popup should open with the operation button to open of close that valve. When a valve is opened it should be colored green and when its closed it should be colored gray or something. The Tank class has a couple of methods:
    drawTank(); to draw the tank in my applet,
    openValve(); to open the Valve,
    closeValve(); to close the Valve,
    After all this is created i want to be able to use this class in all my other classes and create a tank by simple making a new Tank object, draw it on my applet using the drawTank() method and open or close the Valve using the other 2 methods, however when i open or close the Valve the color of the valve should change so i must be able to call the repaint of all the classes that use my Tank class, but i want to do that INSIDE my Tank class.
    If there is another way of doing this i would love to hear so, but i would help me a lot if you can explain in a little bit of sample code. It doesn't have to be really long or detailed.
    Thnx in advance

  • Change origin of canvas

    hey, i have a canvas that positions itself in the middle of the screen with two lines (x and y axis). the problem is that i want to be able to move the origin, which then draws the axis again.
    thanks
    Pedge
    // GCanvas.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This class extends the canvas class to include the input and drawing of a polygon
    * @author Geoff Hobson
    * @version 1.1 (24 Nov 99)
    class GCanvas extends Canvas
    * the polygon object associated with this canvas.
    private GPolygon polygon;
    * indicates whether currently in process of colecting the vertices of a polygon.
    private boolean building = false;
    * the size of one pixel in the logical coordinates of the polygon - the scaling factor.
    float pixelSize;
    * the screen x coordinate of the logical origin - screen x position of y-axis.
    int centerX;
    * the screen y coordinate of the logical origin - screen y position of x-axis.
    int centerY;
    * the radius of the circle around the start point,
    * a mouse press anywhere in this circle will be treated as selecting the centre point.
    private int circleSize = 3;
    * Constructs a GCanvas and associates it with the given Polygon poly.
    * @param poly the polygon object which is to be drawn and manipulated
    GCanvas(GPolygon poly)
    polygon = poly;
    addMouseListener
    (new MouseAdapter()
    { public void mousePressed(MouseEvent evt)
    pointSelected(evt.getX(), evt.getY());
    ); // end of new MouseAdapter
    setBackground(Color.gray);
    private int cX, cY;
    * clears the canvas and sets it ready for the input of a new polygon.
    public void newPoly()
    building = true;
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    repaint();
    * The action to be performed when a point is selected by a mouse press.
    * @param x the x coordinate of the selected point
    * @param y the y coordinate of the selected point
    private void pointSelected(int x, int y)
    if (building)
    addVertex(x, y);
    * Add a new vertex to the polygon object
    * @param x the x coordinate of the new vertex
    * @param y the y coordinate of the new vertex
    private void addVertex(int x, int y)
    if (polygon.size() == 0)
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add first vertex to a polygon
    else
    Point2D v0 = polygon.getVertex(0);
    int dx = x - iX(v0.x), dy = y - iY(v0.y);
    if (dx * dx + dy * dy < circleSize * circleSize)
    {    // mouse in circle around first vertex
    polygon.closePolygon(); // the polygon has been closed
    building = false;
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    else
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add an other vertex to polygon
    repaint();
    * Converts logical to screen x coordinate
    * @param x the logical x coordinate
    * @return the screen x coordinate
    int iX(float x)
    return Math.round(centerX + x/pixelSize);
    * Converts logical to screen y coordinate
    * @param x the logical y coordinate
    * @return the screen y coordinate
    int iY(float y)
    return Math.round(centerY - y/pixelSize);
    * Converts screen to logical x coordinate
    * @param x the screen x coordinate
    * @return the logical x coordinate
    float fX(int x)
    return (x - centerX) * pixelSize;
    * Converts screen to logical y coordinate
    * @param x the screen y coordinate
    * @return the logical y coordinate
    float fY(int y)
    return (centerY - y) * pixelSize;
    * Paints the canvas with current state of polygon
    * @param g the graphic context for the paint method
    public void paint(Graphics g)
    // initialise a blank canvas and draw axes etc
    int maxX = getSize().width - 1; // get size of screen
    int maxY = getSize().height - 1;
    float rWidth = polygon.logicalWidth(); // get logical size of polygon
    float rHeight = polygon.logicalHeight();
    pixelSize = Math.max(rWidth/maxX, rHeight/maxY); // calculate scaling factor
    centerX = maxX/2; // calculate position of axes
    centerY = maxY/2;
    int left = iX(-rWidth/2); // calculate edges of logical polygon
    int right = iX(rWidth/2);
    int bottom = iY(-rHeight/2);
    int top = iY(rHeight/2);
    // draw white rectangle for logical polygon
    g.setColor(Color.white);
    g.fillRect(left, top, right - left+1, bottom - top+1);
    // draw frame around logical polygon rectangle
    g.setColor(Color.darkGray);
    g.drawRect(left, top, right - left, bottom - top);
    g.setColor(Color.lightGray);
    g.drawLine(left,centerY, right,centerY); // draw x axis
    g.drawLine(centerX,top, centerX,bottom); // draw y-axis
    // draw current state of the polygon
    int n = polygon.size();
    if (n == 0) return; // if there are no vertices
    Point2D A, B;
    A = (polygon.getVertex(0));
    // Show tiny circle around first vertex:
    g.setColor(Color.red);
    if (!polygon.isClosed())
    g.drawOval(iX(A.x)-circleSize, iY(A.y)-circleSize, circleSize*2, circleSize*2);
    // draw the polygon
    g.setColor(Color.blue);
    for (int i=1; i<n; i++)
    B = (polygon.getVertex(i));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    A = B;
    if (polygon.isClosed()) // draw side from last to first vertex
    B = (polygon.getVertex(0));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    } // end of paint
    } // end of class GCanvas

    How about declaring changing centerx and centery in the constructor?

  • Invoking paint method in Java3D

    I have some example programs in using Java3D but none of them paints 'directly' on the canvas3D.
    if i have a class that extends a Canvas3D how would i call the paint method, can i use this method to draw a 2D polygon on my canvas? (because i wanted to have 3D and 2D objects mixed).
    how would i do this? are the points in terms of x, y, z?
    can anyone help me with this?
    thanks in advance

    I've been trying to do this myself, snd it's a right pain in the arse.
    To actually paint on the Canvas3D, when you override postRender(), you do all your stuff but it doesn't work until you call flush(). However, when I tied it (just drawing a simple rectange), my app slowed from 20fps to 2, which is a bit too much of a performance hit for my liking.
    The J3D Repository overlay is fairly easy to set up, but for some reason the polygon it draws on is about 1 unit away from where you add it, so for a 1st person thing like I'm doing, it dissapears when you get too near a wall. In the end, i have just created my own by putting a texture on a cube just in front of the viewport.

Maybe you are looking for

  • ITunes doesn't play.... what's up??

    Ok, this is weird but I'm afraid the answer might be both obvious and tragic. All of a sudden, iTunes quit working completely, except that everything about it looks perfectly normal. It's not frozen, I can click on my playlists, I can drag the time b

  • WRT120N for gsm and pc

    Hello, i've got the following problem/question. I have W-less router WRT120N and i'm using it for WLAN connection for one laptop. My internet provider has restricted the TTL and i can't share internet between more computers. But i'm wondering if i ca

  • What is the default username and password for a Airport Time Capsule 3TB

    What is the default username and password for a Airport Time Capsule 3TB

  • How did Adobe auto update my credit card info??

    Hi, I have an issue with Adobe currently. This has happened twice now during my one-year CC subscription. I had to cancel my credit card due to fraudulent charges not associated with Adobe and as a result wasn't able to update my credit card info or

  • Suggestion: make UTF8 as default encoding

    JDeveloper still uses "System default" encoding for editor and compiler, not UTF8. Other tools, like IDEA uses UTF8 more than 5 years. JDeveloper can be ajusted to use UTF8, but it is needed to make this in 3 places at last. If a new developer will n