Line coordinates

I am developing a GUI in using Java Swing. In that I can draw lines or different shapes. I need to click on a line and get its end coordinates on a text field. Can anyone help me out?

I am developing a GUI in using Java Swing. In that I
can draw lines or different shapes. I need to click
on a line and get its end coordinates on a text
field. Can anyone help me out?Sure, start here:
Creating a GUI with JFC/Swing
http://java.sun.com/docs/books/tutorial/uiswing/
When you have a specific question, post it in the swing forum:
http://forum.java.sun.com/forum.jspa?forumID=57
Good luck.

Similar Messages

  • How to clear overlay line

    I would like to clear a line drawn using IMAQ Overlay Line without clearing all overlays (using IMAQ Clear Overlay).  I tried using Overlay Line with the Transparent color (using the same line coordinates) and this did not work.  Anyone have any suggestions?
    Thanks

    Sandor a écrit:
    I would like to clear a line drawn using IMAQ Overlay Line without clearing all overlays (using IMAQ Clear Overlay).  I tried using Overlay Line with the Transparent color (using the same line coordinates) and this did not work.  Anyone have any suggestions?
    Thanks
    A simple trick is to copy the overlay to another empty image, and to copy back this overlay to erase any posterior modification. The attached vi demonstrate this solution. An alternative would be to construct an array in witch all the additions to the overlay would be stored, and to redraw the overlay from scratch using this array.
    Message Edité par chilly charly le 08-31-2005 05:38 AM
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Save Overlay.vi ‏93 KB

  • I want to know how to draw arrows & dashed lines in a picture control

    I have to draw arrows & dashed lines in a picture control. Just like we can do that in word or paint etc. I need to do the same using the mouse and drag the line/arrow till I realease the mouse. I am able to this for a normal line ( it works perfectly) but when I have to draw an arrow or a line I am stumped.

    Unfortunately, you have to code your own VIs to do these. It's not going to be too complicated if you manage the animation (while dragging the mouse) with a normal line and draw the dashed line/arrow at the end (when releasing the mouse button).
    In both cases, you'll know start/end line coordinates, thus having the line equation. For arrows, you need to calculate the angle in order to draw it properly.
    A simpler solution may be an activeX control with these features (Paint like) already integrated or to develop one in Visual Basic (at least it will be simpler to manage mouse events and drawing tasks).
    Let's hope somebody already did it and wants to share.

  • Draw a line after zoom in

    Hi All,
    I want to draw a line after zooming in/out the image. If the image is not scaled, then ever thing is fine. But once I scaled the image and draw the line, the position is not coming correctly. Can you correct me, what's my mistake?
    package imagetest;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ZoomAndDraw extends JPanel
        private java.awt.image.BufferedImage image = null;
        private Line2D.Double line = null;
        private double scale = 1.0;
        private int value = 16;
        private double translateX = 0.0;
        private double translateY = 0.0;
        private MouseManager manager = null;
        public ZoomAndDraw()
            line = new Line2D.Double();
            readImage();
            manager = new MouseManager(this);
            addMouseListener(manager);
            addMouseMotionListener(manager);
        private void readImage()
            try
                image = javax.imageio.ImageIO.read(new java.io.File("D:/IMG.JPG"));
            catch (Exception ex)
        @Override
        public Dimension getPreferredSize()
            if (image != null)
                int w = (int) (scale * image.getWidth());
                int h = (int) (scale * image.getHeight());
                return new Dimension(w, h);
            return new Dimension(640, 480);
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            if (image == null)
                return;
            double x = (getWidth() - scale * image.getWidth()) / 2;
            double y = (getHeight() - scale * image.getHeight()) / 2;
            g2.translate(x, y); // move to center of image
            g2.scale(scale, scale); // scale
            translateX = 0 - x * (1 / scale);
            translateY = 0 - y * (1 / scale);
            g2.translate(translateX, translateY); // move back
            g2.drawImage(image, 0, 0, this);
            g2.setColor(Color.RED);
            g2.draw(line);
            g.dispose();
        public void setLine(Point start, Point end)
            line.setLine(start, end);
            repaint();
        public void addLine(Point start, Point end)
            line.setLine(start, end);
            repaint();
        public void ZoomIn()
            value++;
            scale = (value + 4) / 20.0;
            revalidate();
            repaint();
        public void ZoomOut()
            if (value <= -3)
                return;
            value--;
            scale = (value + 4) / 20.0;
            revalidate();
            repaint();
        class MouseManager extends MouseAdapter
            ZoomAndDraw component;
            Point start;
            boolean dragging = false;
            public MouseManager(ZoomAndDraw displayPanel)
                component = displayPanel;
            @Override
            public void mousePressed(MouseEvent e)
                start = e.getPoint();
                dragging = true;
            @Override
            public void mouseReleased(MouseEvent e)
                if (dragging)
                    component.addLine(start, e.getPoint());
                    component.repaint();
                dragging = false;
            @Override
            public void mouseDragged(MouseEvent e)
                Point end = e.getPoint();
                if (dragging)
                    component.setLine(start, end);
                    component.repaint();
                else
                    start = end;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ZoomAndDraw zoomAndDraw = new ZoomAndDraw();
            //Zoom in call
            zoomAndDraw.ZoomIn();
            zoomAndDraw.ZoomIn();
            zoomAndDraw.ZoomIn();
            frame.add(zoomAndDraw);
            frame.setPreferredSize(new Dimension(640, 480));
            frame.setSize(new Dimension(640, 480));
            frame.setVisible(true);
    }Thanks and Regards
    Raja.

    Hi,
    I'm having one more doubt. Just assume, after calling the ZoomIn(), I am drawing a line.
    Subsequent ZoomIn() calls (let's say 5 times), changed the actual line position. How do I synchronize the zoom in call with the line coordinates?
    public void FireZoomIn()
            new Thread(new Runnable()
                public void run()
                    try
                        Thread.sleep(3000);
                    catch (InterruptedException iex)
                    int count = 0;
                    while (count++ < 5)
                        ZoomIn();
            }).start();
    public void mouseReleased(MouseEvent e)
                if (dragging)
                    component.addLine(start, e.getPoint());
                    component.repaint();
                    component.FireZoomIn();
                dragging = false;
            }Thanks and Regards
    Raja.

  • Changing coordinate updates waveform chart?

    Hi All, hope everyone is having a wonderful 4th of July.
    Alright, so I am new to labview and finding my things around the simple things pretty well, but having never taken any sort of programming interest, Im a bit behind in machine logic, so I figured I would ask here. 
    EDIT: using labview 2009.  Have Vision package
    The research I am doing involves analyzing Electron Speckle Pattern Interferometry (ESPI) images and their fringes to observe fracture points/potential weaknesses in different materials and such.  I have made a simple VI which allows me to draw a line on the ESPI image and output the light intensities to a waveform chart to make it easier to objectively determine the size of the plastic region (area where fracturing is most likely to occur).
    What I would like is to be able to draw or set the coordinates of the line initially, then somehow be able to move it vertically -- using either simply my mouse or a numeric controller -- and have the waveform chart update in real time as i do it. 
    Any suggestions?  Ive attatched my programs, the one called "line.vi" uses numeric input to determine the line coordinates. 
    Also, since i dont sem to be able to attach bitmaps, ive uploaded a sample image here http://img594.imageshack.us/img594/3566/espiimage.png  I dont know why imageshack converted it to a PNG though
    thanks all
    Solved!
    Go to Solution.
    Attachments:
    line.vi ‏50 KB
    light intensity line.vi ‏47 KB

    Hi itschad,
    did you read the context help of the chart? There it is shown what datatype you need to wire to plot more than one curve on the some chart...
    "This made a weird issue where once I select the line, the intensity profile keeps adding itself over and over again onto the end of the chart, so a chart that might initially have been 100 datapoints, just keeps getting longer and longer."
    This is how charts work. They keep a history (that you constantly clear). You can set the size of the history buffer. If the default of 1024 points is too much for you you may decrease this to 100 - it's just a right-click away... Otherwise you should use a graph, as a graph only plots the points that are currently wired to it (it doesn't keep a history of previous values).
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    test horizontal shift.vi ‏48 KB

  • Line gauge

    Hi,
    I am a newby to labview and trying to use 'IMAQ line gauge' function but I haven't managed it yet.
    Could anyone send me any examples or applications ,if there exists any, including 'IMAQ line gauge' function?
    Best regards,
    Solved!
    Go to Solution.

    Hi abligi,
    -IMAQ line gauge is a combination of IMAQ caliper(to certain extent) and IMAQ point to point distances
    -As you can see in help file, you can get Point-Point, Edge-edge,edge-point and point-edge distances.
    -Attaching simple example along with image to give distances.Try playing around by changing line coordinates and type of measurement you need.
    -Adding the snippet also.
    Thanks
    uday,
    Please Mark the solution as accepted if your problem is solved and help author by clicking on kudoes
    Certified LabVIEW Associate Developer (CLAD) Using LV13
    Attachments:
    Line-gauge.vi ‏47 KB
    image.png ‏3 KB
    Line-gauge.png ‏59 KB

  • Saving coordinates in ArrayList

    Hii all,
    I'm having multiple lines, and I need to store those line coordinates anyway so that the lines can be redrawn. I' m trying ArrayList but dont know how to store those coordinates, could you else please help me out !!
    thanks
    Dev

    Hello :
    thanks for your reply... Actually, what I did so far is:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Line2D;
    import java.util.ArrayList;
    import java.util.Vector;
    import javax.swing.JLabel;
    public class DrawFrame extends javax.swing.JFrame implements MouseListener, MouseMotionListener
        double x0, y0, x1, y1;
        private Vector v;
        private JLabel l1;
        private boolean initLine = true;
        //private double[][] coorList;
        public DrawFrame()
            initComponents();
            v = new Vector();
            l1 = new JLabel("FFFF")
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.draw(new Line2D.Double(x0, y0, x1, y1));               
            l1.setSize(new Dimension(350,350));
            l1.addMouseListener(this);
            l1.addMouseMotionListener(this);
            add(l1);
            //coorList = new double[][];
        public void lineOperation(MouseEvent e)
            Graphics g = l1.getGraphics();
            if(initLine)
                setGraphicsDefaults(e);
                Graphics2D g2d = (Graphics2D)g;
                g2d.draw(new Line2D.Double(x0, y0, x1, y1));           
                initLine = false;
            if(mouseHasMoved(e))
                Graphics2D g2d = (Graphics2D)g;
                g2d.draw(new Line2D.Double(x0, y0, x1, y1));
                x1 = e.getX();
                y1 = e.getY();
                g2d.draw(new Line2D.Double(x0, y0, x1, y1));
        public void releaseLine()
            if(Math.abs(x0 - y0) + (Math.abs(x1 - y1)) != 0)
                initLine = true;
                Graphics g = l1.getGraphics();
                Graphics2D g2d = (Graphics2D)g;
                g2d.draw(new Line2D.Double(x0, y0, x1, y1));
        public void mouseDragged(MouseEvent e)
                x1 = e.getX();
                y1 = e.getY();
             lineOperation(e);           
        public void mousePressed(MouseEvent e)
        public void mouseReleased(MouseEvent e)
         releaseLine();
        public void mouseMoved(MouseEvent e)
        public void mouseClicked(MouseEvent e)
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public boolean mouseHasMoved(MouseEvent e)
            return (x1 != e.getX() || y1 != e.getY());
        private void setGraphicsDefaults(MouseEvent e)
            x0 = e.getX();
            y0 = e.getY();
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 469, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 395, Short.MAX_VALUE)
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new DrawFrame().setVisible(true);
    }Here, when ever I drag mouse pointer, lines are drawn. Now I want to redraw those lines, that is why I want to save those line coordinates.
    please help !!
    thanks again
    Dev.

  • Can someone test my Java 2D application? Something gone abit weird/wrong..

    Hi there
    I have just written a Java 2D Graphics Application. I think its complete but the problem is when i run it, it come out with weird result.
    Below is my code:
    import java.awt.*;
    import javax.swing.*;
    public class GraphicsView extends JPanel{
         private double px = 50;
         private double py = 50;
         private double qx = 200;
         private double qy = 50;
         private double rx = 50;
         private double ry = 200;
         private double sx = 200;
         private double sy = 200;
         public GraphicsView(){
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              g.drawLine((int)px, (int)py, (int)qx, (int)qy);
              g.drawLine((int)px, (int)py, (int)rx, (int)ry);
              g.drawLine((int)qx, (int)qy, (int)sx, (int)sy);
              g.drawLine((int)rx, (int)ry, (int)sx, (int)sy);
              double u = 0.1;
              for(int k = 0; k < 55; k++){
                   px = ((1 - u) * px) + (u * qx);
                   py = ((1 - u) * py) + (u * qy);
                   qx = ((1 - u) * qx) + (u * sx);
                   qy = ((1 - u) * qy) + (u * sy);
                   sx = ((1 - u) * sx) + (u * rx);
                   sy = ((1 - u) * sy) + (u * ry);
                   rx = ((1 - u) * rx) + (u * px);
                   ry = ((1 - u) * ry) + (u * py);
                   g.drawLine((int)px, (int)py, (int)qx, (int)qy);
                   g.drawLine((int)qx, (int)qy, (int)sx, (int)sy);
                   g.drawLine((int)sx, (int)sy, (int)rx, (int)ry);
                   g.drawLine((int)rx, (int)ry, (int)px, (int)py);
    import java.awt.*;
    import javax.swing.*;
    public class Program extends JFrame {
         public Program(){
              makeStuff();
         public void makeStuff(){
              setPreferredSize(new Dimension(350,300));
              getContentPane().add(new GraphicsView());
              pack();
              setVisible(true);
            public static void main(String[] args) {
              Program program = new Program();
    }The problem is that:
    When i maximise it the 2D drawing appears weird, out of position, fuzzy & totally messed up! AND when i minimize it back to original window frame size - The 2D drawing totally disappeared/Gone!!!
    Anyone know why is that a problem?
    Is it a Swing problem? Or Java 2D problem?
    oh- above 2 segments of code represent a class each respectively...

    You're trying to do program logic within the paintComponent method. When your paintComponent method ends, lord knows what the final value of your different x and y variables are. They certainly aren't the same values as when you first did the drawing. What ends up happening is that hte drawing is likely done, but is very very small. Throw in some System.out. println's and you'll see.
    I recommend that you do all your equations outside of the paintComponent, and save the line coordinates in an ArrayList of objects of a class you can create. Then have the paintComponent simply iterate through the arraylist drawing based on the values in the objects held by the list.
    Edit: one easy object to use is a Line2D and then have your arraylist hold these objects. Then simply use a Graphics2D object to draw all the Line2D's held in the list.
    Edited by: Encephalopathic on Oct 7, 2008 8:33 PM

  • Problem with computing Font width while printing in Landscape mode

    I have an application which prints a table and fills it with some text. I render it on a JComponent using the drawString(theStr, xPos, yPos) and the drawLine(rigtX, topY, rigtX, botY) methods in Graphics2D object. I want to take print-out of the table and also store the image of the table in, say, jpeg format. The print can be in Landscape or Portrait format depending on the size of the JComponent, which the user sets depending on the table size and the font size.
    I have a paintTable( ) method which contains all the drawString( ) and drawLine( ) methods. This method is called from the paint( ) method of the JComponent to achieve normal rendering. The same method is called to get a BufferedImage of the Table. The same method is further called from the implementation of print( ) method from the Printable interface.
    In the paintTable( ) method, I compute the pixel coordinates of the table grid lines and the texts positions in the tables depending on the font width and height obtained as shown below:
            // Set the Font             
            Font theFont = graphics.getFont();
            theFont = theFont.deriveFont((float)TableFontSize); // TableFontSize is an int of value 8,9,10 etc.
            graphics.setFont(theFont);
            // Get the Font Size      
            FontRenderContext frc = graphics.getFontRenderContext();
            float width = ((Rectangle2D.Float)theFont.getMaxCharBounds(frc)).width;
            float height = ((Rectangle2D.Float)theFont.getMaxCharBounds(frc)).height;
           System.out.println("FONT WIDTH HEIGHT [" + width + "," + height + "] ");I am getting the following value of width and height when the above print statement is executed with a value of 9 for TableFontSize. FONT WIDTH HEIGHT [18.0,11.3203125]
    The problem I face is :
    While Printing in Landscape mode the value of the 'width' variable printed as given above is becoming negative. Kindly see the values: FONT WIDTH HEIGHT [-9.37793,11.3203125]. This is happening ONLY DURING PRINTING IN LANDSCAPE MODE. This makes my calculation of table grid line coordinates and text positions completely wrong and the table goes out of place.
    Kindly note that, there is no problem during normal rendering and BuffereredImage creation and also while printing in Portrait mode. The problem happens irrespective of Linux or Windows. The value of 'height' is always correct.
    Kindly let me know: If the method I use to get the 'width' and 'height' is correct ? Is there any better way which will work fine in all platforms under all circumstances.
    Kindly help me to sort out this issue.
    Thanks a lot in advance and best regards
    -acj123

    I have extracted the relevent code and made a stand alone program.
    The complete code is enclosed; including that for printing.
    Kindly go through the same and help me to solve this problem.
    Thanks again and regards
    -acj123
    import java.awt.*;
    import java.util.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.print.PrinterJob;
    import java.awt.font.FontRenderContext;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class MyCanvas extends JComponent implements Printable, ActionListener
        int TableFontSize = 9;
        private Graphics2D graphics;
        public MyCanvas(JFrame frame)
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(this, BorderLayout.CENTER);
            frame.setJMenuBar(createMenuBar());
        public JMenuBar createMenuBar()
            JMenuBar menubar = new JMenuBar();
            JButton printButton = new JButton("Print");
            menubar.add(printButton);
            printButton.addActionListener(this);
            JButton imageButton = new JButton("Image");
            menubar.add(imageButton);
            imageButton.addActionListener(this);
            JButton drawButton = new JButton("Draw");
            menubar.add(drawButton);
            drawButton.addActionListener(this);
            JButton closeButton = new JButton("Close");
            menubar.add(closeButton);
            closeButton.addActionListener(this);
            return menubar;
        public void actionPerformed(ActionEvent evt)
            String source = evt.getActionCommand();
            if  (source.equals("Close"))
                System.exit(0);
            if  (source.equals("Image"))
                getImage();
                return;
            if  (source.equals("Print"))
                printCanvas();
                return;
            if  (source.equals("Draw"))
                repaint();
                return;
        public BufferedImage getImage()
            Dimension dim = getSize();
            BufferedImage image = (BufferedImage)createImage(dim.width, dim.height);
            this.graphics = (Graphics2D)image.createGraphics();
            System.out.print("\nImage ");
            paintCanvas();
            return image;
        public void paint(Graphics graph)
            this.graphics = (Graphics2D)graph;
            System.out.print("\nDraw  ");
            paintCanvas();
        public void paintCanvas()
            // Set the Font      
            Font theFont = graphics.getFont();
            theFont = theFont.deriveFont((float)TableFontSize);
            graphics.setFont(theFont);  
            // Get the Font Size       
            FontRenderContext frc = graphics.getFontRenderContext();
            float width = ((Rectangle2D.Float)theFont.getMaxCharBounds(frc)).width;
            float height= ((Rectangle2D.Float)theFont.getMaxCharBounds(frc)).height;
            System.out.print("FONT WIDTH HEIGHT [" + width + ", " + height + "] ");
            System.out.print(" SIZE "+ super.getWidth() +", "+ super.getHeight());
        public int print(Graphics graph, PageFormat pageFormat, int pageIndex)
            throws PrinterException
            if (pageIndex > 0) return Printable.NO_SUCH_PAGE;
            this.graphics = (Graphics2D)graph;
            graphics.translate(0,0);
            paintCanvas();
            return Printable.PAGE_EXISTS;
         *  Interface method for Printing the Canvas on Paper
        public void printCanvas()
            PrinterJob printJob =  PrinterJob.getPrinterJob();
            printJob.setPrintable(this);
            PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
            if (super.getWidth() < super.getHeight())
                System.out.print("\nPrint PORTRAIT ");
                attr.add(OrientationRequested.PORTRAIT);
            else
                System.out.print("\nPrint LANDSCAPE ");
                attr.add(OrientationRequested.LANDSCAPE);
            Dimension dim = getSize();
            attr.add(new MediaPrintableArea(1, 1, dim.width, dim.height,
                                                  MediaPrintableArea.MM));
            attr.add(new JobName("MyCanvas", Locale.ENGLISH));
            attr.add(new RequestingUserName("acj123", Locale.ENGLISH));
            if (printJob.printDialog(attr))
                try
                    printJob.print(attr);
                catch(PrinterException ex)
                    ex.printStackTrace();
        public static void main(String[] arg)
            JFrame frame = new JFrame("MyFrame");
            MyCanvas canvas = new MyCanvas(frame);
            frame.setSize(800, 600);
            frame.setVisible(true);
    }

  • Need some help in HttpURLConnection

    Hi,
    I am having trouble with the HttpURLConnection and hope someone could help me with this. I have the following code, which reads lines of data from a file and each time a line is read, I want to send the data across to a servlet.
    String urlString = "http://leewse:8080/vms/tracking.srv";
              try {
                   URL url = new URL(urlString);
                   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                   conn.setRequestMethod("GET");
              conn.setUseCaches(false);
              conn.setDoInput(true);
              conn.setDoOutput(true);
                   DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                   String dataString, line, coordinates, vehicleNumber;
              StringTokenizer stringTokenizer;
                   BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\vms_simulator\\location.txt"));
                   while ((line = bufferedReader.readLine()) != null) {
                   stringTokenizer = new StringTokenizer(line, ";");
                   coordinates = stringTokenizer.nextToken();                    
                   vehicleNumber = stringTokenizer.nextToken();               
                        out.writeBytes("vehicleNumber=" + URLEncoder.encode(vehicleNumber, "UTF-8") +
                        "&from=" + URLEncoder.encode("list", "UTF-8") +
                             "&method=" + URLEncoder.encode("edit", "UTF-8") +
                        "&coordinates=" + URLEncoder.encode(coordinates, "UTF-8"));
                   out.flush();
                   //out.close();
                   System.out.println(conn.getContentType());
                   System.out.println(conn.getResponseMessage());      
                   conn.disconnect();     
              catch (MalformedURLException e) {
                   e.printStackTrace();
              catch (IOException e) {
                   e.printStackTrace();
    However, I observed that only the first line of data is successfully sent over to the servlet, while subsquent lines of data are not. Could someone please kindly point out where I went wrong? Thanks.

    I have figured out what is causing the "Exception in thread "main" java.lang.NoClassDefFoundError". Apparently, HttpClient requires the commons logging in order to work.
    In any case, I have this code:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    public class Simulator {
      public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        PostMethod httppost = new PostMethod("http://leewse:8080/vms/tracking.srv");
        httppost.setContentChunked(true);
        String line, vehicleNumber, coordinates;
        StringTokenizer stringTokenizer;
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\vms_simulator\\location.txt"));          
        while ((line = bufferedReader.readLine()) != null) {
              stringTokenizer = new StringTokenizer(line, ";");
              coordinates = stringTokenizer.nextToken();                    
              vehicleNumber = stringTokenizer.nextToken();               
              httppost.setParameter("vehicleNumber", vehicleNumber);
              httppost.setParameter("coordinates", coordinates);
              try {
                   client.executeMethod(httppost);
                   if (httppost.getStatusCode() == HttpStatus.SC_OK)
                        System.out.println(httppost.getResponseBodyAsString());
                   else
                        System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
              finally {
                   httppost.releaseConnection();
    }In any case, here are two things about this code:
    1. It can now talk to the servlet for more than once, but the problem is, the parameters cannot be retrieved at the servlet, meaning req.getParameter() always return null. What could be the reason for this?
    2. It also causes a lot of sessions to be created, just like HttpURLConnection. So it seems like it makes no difference to use HttpURLConnection or HttpClient when it comes to resolving my concern? Are HttpURLConnection and HttpClient built on the concept of "one-session-one-request-only"?

  • Sketch erased in AWT panel

    hai
    I have a very strange problem:
    I am presently working on drawiing a sketches on a panel using a PC tablet...
    the scenario is like this:- I have created a Frame and in that I have created a Panel , the screen coordinates of which are scynchronized to those of the PC tablet. At the bottom of the panel there is an OK button.
    Now as soon as I draw something on the tablet, I display it on the Panel.
    Now when I have completed drawing and when I press ok, I get a dialog box to display a message.
    what is the problem now is I see the dialog box, the sketch in the background i.e. on the Panel is erased.
    Can any one tell me what can be the problem with my interface......It will be extremely useful for me......thank you
    best wishes

    You're probably doing the painting in your MouseEventListeren?
    If so you have two ways to go, the easier one, and the one I would use, cause it's more "clean".
    The easier one is to use double-buffering (read about it on the http://java.sun.com) and do the painting in your EventListeren but do it on the offscreen-buffer, and just call repaint().
    The more difficult one is to build a model that holds all the data about the picture, that allows to reproduce it. In your case it would be probably just line coordinates plus colors. And in the EventListeren instead of doing all the painting, just add the new line to the model, and call repaint(). The actuall painting would be done in the paintComponent(Graphics g) method, where you should write a code that would paint your picture based on the data model.
    Hope it helps,
    Marcin

  • Recognizing Objects - Pls help me

    I want to recognize objects in the image (jpg, bmp etc). For example I want to recognize flight object (it is in any angle or scaled or transformed) from the image.
    I started with edge detection and now I don't how to proceed with this. Can anyone help me.
    If you have any website links pls suggest me.
    Regards,
    namanc

    Ok, so you have transported your image to set of black-and-white pixels which denotes edges.
    I assume, object (template) you want to recognize has a well defined and constant "in shape" independently of rotation/scalling/transposition set of edges.
    Now, you need to convert your bitmapped edge image to mathematical image. Mainly you need to detect lines and store their coordinates somewhere.
    Same should be done for you template to search.
    At this step, you have two sets of lines denoting edges: one for searched template and one for image to be searched in.
    In next step you need to formulate a function, which will describe how much a line of you template edge is "similar" to line of searched image. This should be a function of edge number, rotation, scale and translation of your object. It should return 0 if lines are ideally the same, otherwise should return a positive only values. It should be relatively simply, since you will need to differentiate it in symbolic way. For example it can be:
    q = (xi1 - xp1(fi,dx,dy,scale))^2 + (xi2 - xp2(fi,dx,dy,scale))^2 +(yi1 - yp1(fi,dx,dy,scale))^2+(yi1 - yp1(fi,dx,dy,scale))^2
    where xi, yi are searched image lines coordinates, xp,yp are coordinates of edge in image you are looking for, fi,dx,dy,scale are transform parameters.
    Now, you need to find such:
    1. assignment of template edges to image edges
    2. template transformation
    so that SUM(q(all-edges)) is minimum.
    start:
    Assumming, you start at transformation dx,dy,fi,scale you may find best matched image line trying each of template lines with each of image lines and choose best. Then, if SUM(q) does not satisfy you, you should calculate:
    dq/dfi
    dq/ddx
    dq/ddy
    dq/ddscale
    (you have done it symbolic).
    You need to find sumaric value of those equations in current transformation. Then you need to modify arbitrary chosen coordinate in the way, that total q goes smaller. In example, if SUM(dq/ddx) < 0 then you need to enlarge dx, if SUM(dq/ddx) >0, you need to make dx smaller.
    After you find new coordinates, goto start. :)
    Sooner or later (rather later) this algorithm will find best matched region and transformation. Ofcourse you should be smarter than me and be able to find some tricks to speed it up. For example, instead of matching lines denoting edges, you may match corners (points where lines edge are close enough and almost perpedicular). The better starting point you find, the faster it will find result. You may use denstiy functions, color matching or whatever comes to mind.
    The presented method is a "brutal force" search.
    If however, your template does not have well defined edges (blobs, faces, etc) you rather should search another algorithm. If it has a specifc color, make use of it.

  • If/else movie attachment

    URL:
    http://www.driveakamai.org/
    --> click on Interactive Map in navigation
    DESIRED MOD:
    Replace default blue "i" button with red "i" where
    applicable.
    DETAILS:
    The line coordinates are drawn from items in an xml file. The
    "i"
    button is there to pop up an info box within the movie. Items
    from the XML file read something like this for a default item with
    a blue "i":
    <item>
    <title>Moana Vista</title>
    <description>Kapiolani Blvd.: No project related lane
    closures
    scheduled</description>
    <link>
    http://www.driveakamai.org/main/trafficadvisories.cfm</link>
    <isNewUpdated>no</isNewUpdated>
    <Alert>no</Alert>
    <projectID>P19</projectID>
    <Location>Kapiolani Blvd.: No project related lane
    closures scheduled</Location>
    <Time></Time>
    <typeOfProject>Day</typeOfProject>
    <typeOfWork></typeOfWork>
    <publish>yes</publish>
    <date>1/29/2008</date>
    <coordinates>green=1178,812.3s|1108,809.15|1078,795.45|</coordinates>
    </item>
    Some new items will have a <weekend> attribute, which
    will call a red "i" button, and will read as such:
    <item>
    <title>Moana Vista</title>
    <description>Kapiolani Blvd.: No project related lane
    closures
    scheduled</description>
    <link>
    http://www.driveakamai.org/main/trafficadvisories.cfm</link>
    <isNewUpdated>no</isNewUpdated>
    <Alert>no</Alert>
    <projectID>P19</projectID>
    <Location>Kapiolani Blvd.: No project related lane
    closures scheduled</Location>
    <Time></Time>
    <typeOfProject>Day</typeOfProject>
    <typeOfWork></typeOfWork>
    <publish>yes</publish>
    <date>1/29/2008</date>
    <weekend>yes</weekend>
    <coordinates>green=1178,812.3s|1108,809.15|1078,795.45|</coordinates>
    </item>
    QUESTION:
    How do I go about doing this? Attached is what I believe to
    be the code that attaches the blue button. Can anyone give me some
    pointer(s) on this?
    Thanks!

    Consider this your opportunity to learn some Actionscript and take a shot at solving it. 
    For starters, realize that you need to be in control of both hands at the same time, so both of them need to have their own "targetX" and "targetY" properties that you continuously direct them to - One gets directed to a fixed location (its nesting position) and the other follows the mouse.  So start off by having sets of code for each.
    Then think about what role mouseX/mouseY play in determining whether to have the left hand or the right hand following the mouse and create the code for it... at what values should the shift of control occur... add the code in and try things until it works.
    The MOUSE_LEAVE listener/handler role will need to be changed to apply nesting to both.

  • Exporting line end point coordinates?

    Hi,
    I'm in desperate need of a script to export the coordinates of lines, or paths, it doesn't really matter, into a text document.
    I've set my ruler up so the 0,0 is in the center of the image, because I need both 0,0 and -0,-0 to work for what I have in mind, basically using a document as a large Cartesian grid, which you can then extract coordinates of 'edges' or end points of lines from.
    A little background on why I need it, for anyone curious. I figured out a way to build new worlds/maps for a game that generates terrain based on 'boundaries', which are drawn on, in a 2d plane, but I need coordinates to map these boundaries correctly. I could do it manually, where I'd hover my mouse over every edge or end of the line point, but this would save a LOT of time.
    I'd be insanely grateful if anyone can help me out. I've tried looking for scripts or other software, but haven't been successful at all for what I really need.
    The way I have my document setup is, 1 pixel per cm, 16384x16384cm. It's quite large, so most 'graph' software won't work for it. The grid itself works fairly well, I just need a decent way to export the coordinates from it.
    Thanks in advance!
    Edit:
    Here, I made an example of a rectangle to give you guys the idea of which coordinates I'd need:
    http://i.imgur.com/VILOwrL.png

    Don't appologize, I was stuck on cm because I thought there wasn't another way, I only figured out after JJMack mentioned it, that it's possible purely by pixels.
    First time working with coordinates, I'm in total new territory.
    The above works great, except now I've stumbled across 2 new problems, sorry to make it so complicated!
    What I have now, slightly tweaked what you gave me:
    var dataFile = new File('~/desktop/exportData.txt');
    var doc = app.activeDocument;
        for(var c =0; c<doc.layers.length;c++){
           doc.activeLayer= doc.layers[c];
    var pathItem = doc.pathItems[doc.pathItems.length-1];
    var dataStream = "";
    for(var subPathIndex = 0;subPathIndex<pathItem.subPathItems.length;subPathIndex++){
        for(var pointIndex = 0;pointIndex<pathItem.subPathItems[subPathIndex].pathPoints.length;pointIndex++){
                    dataStream = dataStream+doc.activeLayer.name+'\t';
            dataStream = dataStream+pathItem.subPathItems[subPathIndex].pathPoints[pointIndex].anchor+'\t'+'\r';
            dataStream = dataStream+'\r';
    dataFile.open('w');
    dataFile.write(dataStream);
    dataFile.close();
    But this outputs this:
    Background     4222,0
    Background     2963,-3550
    Background     4330,-4210
    Background     6450.3937,-2459
    Background     6141,2387
    Background     4834,2891
    Background     3970,924
    Which made me realize, that the paths aren't bound to a layer (It's been a while since I've used paths), so it'll just use the Background layer. There is no way around that, right? Since this script only targets layers, it'll ignore path names, which brings me to another question, is it possible to use the same thing, only for saved paths? So if you had 2 paths, one named P1 and the other P2, that it would display it like:
    P1     4222,0
    P1     2963,-3550
    P1     4330,-4210
    P1     6450.3937,-2459
    P2     6141,2387
    P2     4834,2891
    P2     3970,924
    And the other thing, because I'm using a loop now, which basically repeats the \r after ever coordinate, there isn't a way to collect all coordinates and display them in a chain, basically, and then using the \r after all the coordinates for one path is exported, before it moves on to the next path, or? Basically like the post previous to this, except with paths, instead of layers.
    Thank you guys so much for helping me though, would been completely lost without it.

  • How can I get the coordinates to draw a line?

    Hi,
    I want to draw a line. Here is a part of my Quell-code.
    public class Map extends JFrame {
    public Map() {
    super("Map");
    setSize(340, 340);
    MapPane map = new MapPane();
    getContentPane().add(map);
    class MapPane extends JPanel {
    public void paintComponent(Graphics comp) {
    Graphics2D comp2D = (Graphics2D)comp;
    comp2D.drawLine(0,0,340,340);
    Now, the line begins exactly top left in the edge, but ends not exactly down right in the edge of my Frame. Is there any possibility to determine the exact coordinates of the frame. I thought, if the size of the window is set by the setSize-Method to (340,340), the line ends exact
    in the edge (down right). See: comp2D.drawLine(0,0,340,340).
    Can somebody give me a piece of advice, please?
    Thanks, joletaxi

    Have you tried the getWidth() and getHeoght() methods to determine how long the line should be?

Maybe you are looking for