Draw a line on a JFrame

I have 2 panels inside a JFrame and I want to separate the 2 panels using a visible line. How can I draw this line?

You will need to over ride the paint(Graphics g) method.
From there you can use the g.drawLine(startX,startY,endX,endY). So for instance if you had two panels next to each other and the line is a vertical line then you would do something similar to this.
public void paint(Graphics g){
        super.paint(g);
        int x = this.jPanel1.getWidth();
        g.drawLine(x, 0, x, this.getHeight());
}This is probably a good place to start learning java2d
http://java.sun.com/docs/books/tutorial/2d/basic2d/index.html

Similar Messages

  • I need to draw some line over my JFrame

    I draw them using the paint method. The lines are drawn but the JInternal Frame does not show all the other components, JTextFields, JLabels...
    Can please S.O help me?
    my code is:
    public void paint (Graphics2D g)
    g.setColor(Color.black);
    cambiaColor cc = new cambiaColor();
    Font fo;
    fo = new Font ("Arial Unicode MS",Font.BOLD,10);
    g.setFont(fo);
    java.awt.FontMetrics metric = g.getFontMetrics(g.getFont());
    g.drawRect(0,90,450,270);
    g.drawRect(0,100,450,60);
    int ini = Integer.parseInt(((Object[])((Object[])dec.getDatosControlador())[2])[0].toString())-1;
    int fin = Integer.parseInt(((Object[])((Object[])dec.getDatosControlador())[2])[1].toString());
    int rowIni = (int)(ini/8);
    int rowEnd = (int)(fin/8);
    int c=0;
    if ((ini != 0) && (fin !=32))
    for (int i=rowIni;i<=rowEnd;i++)
    if (i>rowIni)
    ini = (8*c);
    if ((i+1)*8>fin)
    g.drawRect((50*(ini%8))+20,(i*63)+95,((50*(fin%8))+20)-((50*(ini%8))+20),63);
    else
    g.drawRect((50*(ini%8))+20,(i*63)+95,425-((50*(ini%8))+20),63);
    c++;
    g.setColor(new Color(204,204,204));
    g.drawLine(10,10,15+metric.stringWidth("Detectores"),10);
    g.drawLine(10,90,15+metric.stringWidth("Grupos"),90);
    g.setColor(Color.black);
    g.drawString("Detectores",15,10);
    g.drawString("Grupos",15,90);
    }

    Take a look at the RootPane tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html
    Specifically at the GlassPane stuff.
    The GlassPaneDemo shown there includes some code where the paint method was modified. I think you can use something like that in your code too.

  • Problem in drawing a line in Java Application Program

    Hi,
    I am trying to draw a line after a message is displayed on the screen. But the line is not at all coming on the screen while running. but I can see a red line is appearing on the screen first and and it is getting overridden.
    There is something wrong in the concept what I understood about graphics.Can anybody help to
    understand where the problem is ?
    Here is the part of the code which used to draw line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.util.Date.*;
    import java.text.*;
    import java.lang.*;
    import MyPack.*;
    class chalan_pay extends JFrame
    JTextField jt1,jt2,jt3,jt4,jt5;
    JLabel jlh,jl1,jl2,jl3,jl4,jl5,jl10;
    JButton bt1,bt2,bt3;
    Choice ch1,ch2,ch3,ch4;
    Connection con = null;
    int i1no,i2no,i3no,i4no,itno;
    String idate;
    public chalan_pay()
    getContentPane().setLayout(null);
    jt1= new JTextField(5);
    jt1.setBounds(110,150,50,20);
    jt2= new JTextField(10);
    jt2.setBounds(400,150,100,20);
    jt3= new JTextField(3);
    jt3.setBounds(590,150,30,20);
    jt4= new JTextField(2);
    jt4.setBounds(750,150,30,20);
    jlh= new JLabel();
    jlh.setText("CHALLAN DETAILS");
    jlh.setBounds(300,50,200,20);
    jl1= new JLabel();
    jl1.setText("IGM No. ");
    jl1.setBounds(50,150,100,20);
    jl2= new JLabel();
    jl2.setText("IGM Date ");
    jl2.setBounds(340,150,100,20);
    jl3= new JLabel();
    jl3.setText("Line No. ");
    jl3.setBounds(530,150,100,20);
    jl4= new JLabel();
    jl4.setText("Subline No. ");
    jl4.setBounds(680,150,100,20);
    jl10= new JLabel();
    jl10.setBounds(100,200,300,20);
    ch1= new Choice();
    ch1.setBounds(170,150,150,20);
    getContentPane().add(ch1);
    ch1.addItemListener(new Opt1());
    bt1= new JButton("Exit");
    bt1.setBounds(200,600,100,20);
    getContentPane().add(bt1);
    bt1.addActionListener(new Ex());
    try
    con=db_connect.getConnection();
    Statement st1 = con.createStatement();
    ResultSet rs1 = st1.executeQuery("select igm_no,to_char(igm_dt,'DD-MON-YY'),line_no,subline_no from "+
    "det_item order by igm_no");
    while(rs1.next())
    ch1.addItem(String.valueOf(rs1.getInt(1))+" "+rs1.getString(2)+" "+
    String.valueOf(rs1.getInt(3))+" "+String.valueOf(rs1.getInt(4)));
    rs1.close();
    st1.close();
    catch(Exception e){e.printStackTrace();}
    getContentPane().add(jlh);
    getContentPane().add(jl1);
    getContentPane().add(jt1);
    getContentPane().add(jl2);
    getContentPane().add(jt2);
    getContentPane().add(jl3);
    getContentPane().add(jt3);
    getContentPane().add(jl4);
    getContentPane().add(jt4);
    getContentPane().add(jl10);
    setSize(900,700);
    setVisible(true);
    show();
    public void paint(Graphics g)
    g.setColor(Color.red);
    g.drawLine(0,300,600,300);
    class Ex implements ActionListener
    public void actionPerformed(ActionEvent evt)
    if(evt.getSource() == bt1)
    dispose();
    return;
    This code is incomplete. The program is compiled and Ran. I am unable to see the Line.
    Is it because , I am using contentPane ?. Please help me to cake it clear.
    mjava

    I have no idea what JTutor is, but if it tells you to override paint() in Swing, it's not worth its disk space.
    [http://java.sun.com/docs/books/tutorial/uiswing/painting/closer.html] clearly says that for all practical purposes paintComponent will be the only method that you will ever need to override.

  • Drawing fading line

    Hello everyone!
    I am trying to draw a fading line on a desktop. For example: we have a JFrame instance on the screen, when we press right mouse button over the frame and drag the mouse across the screen, I want to draw a line, fading through time. I don't want to restrict the line in the JFrame bounds, instead I want to draw it on the desktop screen.
    Any tips or tricks. Thanks in advance.

    If you don't want to restrict the line to a single JFrame, I believe the JLayeredPane is for you. It allows you to have a transparent pane which overlays multiple Swing components.
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLayeredPane.html

  • Drawing a Line in JAVA

    Well Ive got my program to draw a line, but when I drag the mouse across the screen I'd like it to show its actual progress. Ill try to explain this better, if I click my mouse on one point on the screen and drag it to the enxt the line doesnt show up untill I reach my final spot when i release my mouse. What Id like for it to do is to be able to start the line and then have it show the lines progress while Im dragging it. I dont want it to hide the line or whatever. Can anyone give me some help with this? Heres both my java and HTML code.
    Java:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Lab11 extends Applet implements MouseListener {
        int x0, y0, x1, y1;
        public void init() {
         addMouseListener(this);
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e) {
         x0 = e.getX();
         y0 = e.getY();
         System.out.println("Mouse pressed at: (" +
                      x0 + ", " + y0 + ")" );
        public void mouseReleased(MouseEvent e) {
         x1 = e.getX();
         y1 = e.getY();
         System.out.println("Mouse released at: (" +
                      x1 + ", " + y1 + ")" );
         this.repaint();
       public void paint(Graphics g) {
         g.drawLine(x0, y0, x1, y1);
    }HTML:
    <html>
      <head>
        <title>Lab 11 Applets</title>
      </head>
      <body bgcolor=white>
        <applet code="Lab11.class" width=300 height=300>
        </applet>
      </body>
    </html>Thanks guys!

    You forgot to add this to your paint() code ...
    g.setColor(Color.BLACK)
    You'll never see anything drawn unless you set a color different thatn background.
    This works, I added code so you can run it in a frame too because I don't want to be bothered with dealing with applets and html files;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Lab11 extends Applet implements MouseListener, MouseMotionListener {
        int x0, y0, x1, y1;
        //public void init() {
             public Lab11() {
             addMouseListener(this);
             addMouseMotionListener(this);
        public void mouseDragged(MouseEvent e)
             x1 = e.getX();
             y1 = e.getY();
             repaint();
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e) {
         x0 = e.getX();
         y0 = e.getY();
         System.out.println("Mouse pressed at: (" +
                      x0 + ", " + y0 + ")" );
        public void mouseReleased(MouseEvent e) {
         x1 = e.getX();
         y1 = e.getY();
         System.out.println("Mouse released at: (" +
                      x1 + ", " + y1 + ")" );
         this.repaint();
       public void paint(Graphics g) {
            g.setColor(Color.BLACK);
         g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             JFrame f = new JFrame("Test");
             f.getContentPane().add(new Lab11());
             f.setVisible(true);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • Drawing a line in java 1.4

    I am drawing a line using the method
    drawPolyline(int[],int[],int) of the Graphics class.
    It works fine in all cases except when i try to draw
    an exactly vertical line or an exactly horizontal
    line. In these 2 case, it does not draw a line at all.
    All. i can see are the 2 selection end points.
    This works fine in jdk1.3 but not in jdk1.4
    Please lemme know ASAP as to what the problem and what i should do?
    Thanks
    Jatin

    You forgot to add this to your paint() code ...
    g.setColor(Color.BLACK)
    You'll never see anything drawn unless you set a color different thatn background.
    This works, I added code so you can run it in a frame too because I don't want to be bothered with dealing with applets and html files;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Lab11 extends Applet implements MouseListener, MouseMotionListener {
        int x0, y0, x1, y1;
        //public void init() {
             public Lab11() {
             addMouseListener(this);
             addMouseMotionListener(this);
        public void mouseDragged(MouseEvent e)
             x1 = e.getX();
             y1 = e.getY();
             repaint();
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e) {
         x0 = e.getX();
         y0 = e.getY();
         System.out.println("Mouse pressed at: (" +
                      x0 + ", " + y0 + ")" );
        public void mouseReleased(MouseEvent e) {
         x1 = e.getX();
         y1 = e.getY();
         System.out.println("Mouse released at: (" +
                      x1 + ", " + y1 + ")" );
         this.repaint();
       public void paint(Graphics g) {
            g.setColor(Color.BLACK);
         g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             JFrame f = new JFrame("Test");
             f.getContentPane().add(new Lab11());
             f.setVisible(true);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • 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?

  • 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.

  • Draw a line using mouse

    Hello there:
    I'm trying to draw a line using mouse pointer: My code is:
    public class DrawLine extends JFrame implements MouseListener, MouseMotionListener
        int x0, y0, x1, y1;  
        public DrawLine()
             addMouseListener(this);
             addMouseMotionListener(this);
        public void mouseDragged(MouseEvent e)
             x1 = e.getX();
             y1 = e.getY();
             repaint();
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e){ }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e)
              x0 = e.getX();
              y0 = e.getY();           
        public void mouseReleased(MouseEvent e)
              x1 = e.getX();
              y1 = e.getY();
       public void paint(Graphics g)
                 g.setColor(Color.BLACK);
              g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             DrawLine dr=new DrawLine("Test");
             dr.setVisible(true);
             dr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }when mouse is dragged, multiple lines are being drawn....
    could you else please tell me what should I've to do???
    thanks n regards...
    Dev

    You can implement the listeners on any class, even one that (implicitly) extends Object. What matters is that the listener is added to the component that needs to use it.
    That said, why do you want to extend JFrame? Are you adding functionality to the JFrame to justify extending the JFC class? Note that extending JFrame allows the users of your class to access the functionality of a JFrame, is that really indicated here?
    one class that extends JFrame, and one can draw a line on JLabel, embedded within JFrame!So you still have to override paintComponent of the JLabel, which implies using an anonymous inner class.
    Starting with the example already posted, that would be:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    public class DrawLineTest
        implements MouseListener, MouseMotionListener {
      JLabel label;
      int x0, y0, x1, y1;
      private void makeUI() {
        JFrame frame = new JFrame("DrawLineTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel("FFFF") {
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLACK);
            g.drawLine(x0, y0, x1, y1);
        label.setPreferredSize(new Dimension(500, 500));
        label.addMouseListener(this);
        label.addMouseMotionListener(this);
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new DrawLineTest().makeUI();
      public void mousePressed(MouseEvent e) {
        x0 = e.getX();
        y0 = e.getY();      
      public void mouseReleased(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
      public void mouseDragged(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
        label.repaint();
      public void mouseMoved(MouseEvent e) { }
      public void mouseClicked(MouseEvent e){ }
      public void mouseEntered(MouseEvent e) { }
      public void mouseExited (MouseEvent e) { }
    }Better spend more time with the tutorials, there's a separate section on writing event listeners.
    db

  • "I want to draw a line, and it will highlight when I click it."

    I am currently working on a project right now. My project is a structural analysis software for civil engineers. Our project is already at it's infant
    stage of development. I am having trouble with how to implement drawing on a canvas. Heres the specs:
    -There are nodes on the drawing board illustrated by dots.
    -Lines must be drawn connecting the nodes.
    -Nodes must be a separate object where it could respond to mouse
    events.
    -Lines must also be a separate object where it could respond to mouse
    events.
    -Nodes and lines contain mathematical attributes, color information.
    -I can instantly delete a line, or change its attributes by selecting
    it.
    Heres what I have imagined:
    -I am going to draw my Nodes in a JPanel which implements a
    mouseListener.
    -Whenever I want to add nodes to the drawing board, I only have to add
    the Node objects i created.
    No problem with the nodes. Problem is in the lines i will be drawingconnecting one node to another.
    -I tried manual live drawing of the lines as the mouse moves. Now its
    flat on the drawing board. It can't be touched!
    -I still don't have any idea how to implement the line that it could
    respond to mouse events.
    -If I try to draw it in a JPanel with mouseListener, a JPanel is square
    so if I move my mouse to point in to the line drawn on the JPanel, it
    will already respond before the mouse could reach the line image. One
    thing also, it could overlap other JPanels.
    -The JPanel idea came up to my mind coz I thought these objects could
    be
    selectable custom components.
    -Now I realized JPanel is not the ANSWER!
    In simple saying:
    "I want to draw a line, and it will highlight when I click it."
    Stubborn Newbie,
    Edgar

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class SelectingLines extends JPanel
        Line2D.Double[] lines;
        int selectedIndex = -1;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(lines == null)
                initLines();
            for(int j = 0; j < lines.length; j++)
                Color color = Color.blue;
                if(j == selectedIndex)
                    color = Color.green.darker();
                g2.setPaint(color);
                g2.draw(lines[j]);
        public void setSelection(int index)
            selectedIndex = index;
            repaint();
        private void initLines()
            lines = new Line2D.Double[3];
            int w = getWidth();
            int h = getHeight();
            lines[0] = new Line2D.Double(w/8, h/8, w/3, h/6);
            lines[1] = new Line2D.Double(w/3, h/6, w/2, h/2);
            lines[2] = new Line2D.Double(w/2, h/2, w*5/8, h*7/12);
        public static void main(String[] args)
            SelectingLines selectPanel = new SelectingLines();
            selectPanel.addMouseListener(new LineSelector(selectPanel));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(selectPanel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class LineSelector extends MouseAdapter
        SelectingLines selectingLines;
        Rectangle r;
        final int S = 4;
        public LineSelector(SelectingLines sl)
            selectingLines = sl;
            r = new Rectangle(S, S);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            r.setLocation(p.x-S/2, p.y-S/2);
            Line2D.Double[] lines = selectingLines.lines;
            int index = -1;
            for(int j = 0; j < lines.length; j++)
                if(lines[j].intersects(r))
                    index = j;
                    break;
            if(index != selectingLines.selectedIndex)
                selectingLines.setSelection(index);
    }

  • How to see my code drawing a line from one point to another

    hi, im wondering if you could help me.
    i am working on my project which is to visualise travelling salesman heuristics.
    i have managed to make my first heuristic work, but my problem is that when i clicked the run button on my GUI,
    the output is already a complete tour with all the edges already drawn, but what i want is to see how it solves or draw the lines from one vertex to another just by clickin the run button once.
    would be great if you could advice me of what method or technique i need to use to see my application solving the tour or drawing the edges.
    below is my cofe for drawing the edges from one point to another
      void drawLineNNh(Graphics g){
             Graphics2D g2 = (Graphics2D) g;
             g2.setColor(Color.blue);
             int i = 0;
             if (P == null) return;
             else
                 for(i=0; i<P.getSize(); i++)
                 Line2D.Double drawLine = new Line2D.Double(P.x_coor[nnH.seen]+5, P.y_coor[nnH.seen[i]]+5, P.x_coor[nnH.seen[i+1]]+5,P.y_coor[nnH.seen[i+1]]+5);
    Line2D.Double drawLastEdge = new Line2D.Double(P.x_coor[nnH.seen[P.getSize()-1]]+5, P.y_coor[nnH.seen[P.getSize()-1]]+5, P.x_coor[0]+5,P.y_coor[0]+5);
    g2.drawString( " Total Distance : " + nnH.totalDistance , 10, 300);
    g2.draw(drawLine);
    g2.draw(drawLastEdge);
    public void setNNh(Points p)
    nnH = new NNheuristic(p);
    useNNh = true;
    public void paint(Graphics g)
    frame(g);
    drawpoints(g);
    if(useNNh)
    drawLineNNh(g);
    below is my code for calling the above method to draw edges, actionlistererun.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Run")) {
    if (chooseHeur.getSelectedItem()=="Nearest-Neighbour")
    System.out.println(chooseHeur.getSelectedItem());
    //points = new Points(toInt((String)chooseNum.getSelectedItem()));
    //PlotArea.set(points);
    PlotArea.setNNh(points);
    PlotArea.repaint();

    I AM USING SWING.
    HERE IS MY CODE, HOPEFULLY ENOUGH TO UNDERSTAND THE PROBLEM.
    class Plot extends Panel{
         public static int num;
         NNheuristic nnH;
         Closest_insertion CI;
         Points P;
         public static boolean useNNh= false;
         boolean useCI=false;
         boolean triangleDrawn = false;
         boolean CIupdate;
         void drawpoints (Graphics g)
             Graphics2D g2 = (Graphics2D) g;
             Graphics2D g3 = (Graphics2D) g;
             int i=1;
             g2.setColor(Color.red);
                    if (P==null) return;
                    else
                    while (i<P.getSize())
                         Ellipse2D.Double vertices = new Ellipse2D.Double(P.x_coor,P.y_coor[i],10,10);
    g2.fill(vertices);
    i++;
    g3.setColor(Color.MAGENTA);
    Ellipse2D.Double initial = new Ellipse2D.Double(P.x_coor[0],P.y_coor[0],10,10);
    g3.fill(initial);
    System.out.println("No. of Vertices: " + P.getSize());
    for(int k = 0; k < P.getSize(); k++)
    System.out.println("x coordinate: " + P.x_coor[k] + ", " + "y coordinate :" + P.y_coor[k] );
    // System.out.println("next:"+ P.x_coor[k+1]);
    triangleDrawn = false;
    void drawLineNNh(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.blue);
    int i = 0;
    if (P == null) return;
    else
    for(i=0; i<P.getSize(); i++)
    Line2D.Double drawLine = new Line2D.Double(P.x_coor[nnH.seen[i]]+5, P.y_coor[nnH.seen[i]]+5, P.x_coor[nnH.seen[i+1]]+5,P.y_coor[nnH.seen[i+1]]+5);
    Line2D.Double drawLastEdge = new Line2D.Double(P.x_coor[nnH.seen[P.getSize()-1]]+5, P.y_coor[nnH.seen[P.getSize()-1]]+5, P.x_coor[0]+5,P.y_coor[0]+5);
    g2.drawString( " Total Distance : " + nnH.totalDistance , 10, 300);
    g2.draw(drawLine);
    g2.draw(drawLastEdge);
    public void set (Points p)
    P=p;
    useNNh = false;
    useCI = false;
    public void setNNh(Points p)
    nnH = new NNheuristic(p);
    useNNh = true;
    void frame (Graphics g)
    g.setColor(Color.white);
              g.fillRect(0,0,size().width,size().height);
              g.setColor(Color.green);
              g.drawRect(0,0,579,280);
    public void paint(Graphics g)
    frame(g);
    drawpoints(g);
    if(useNNh)
    drawLineNNh(g);
    else if(useCI)
    if(!CIupdate)
    drawTriCI(g);
    else
    drawRestCI(g);
    // drawLineNNh(g);
    public void clear ()
         // remove the points and the graph.
    P=null;
    triangleDrawn = false;
    code of my GUIpublic class TSP extends JFrame{
    JButton run;
    ...................codes...........
    TSP() {
    ...............................codes...........
    run = new JButton ("Run");
    run.setPreferredSize(new Dimension(113,30));
    run.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Run")) {
    if (chooseHeur.getSelectedItem()=="Nearest-Neighbour")
    System.out.println(chooseHeur.getSelectedItem());
    //points = new Points(toInt((String)chooseNum.getSelectedItem()));
    //PlotArea.set(points);
    PlotArea.setNNh(points);
    PlotArea.repaint();
    else if(chooseHeur.getSelectedItem()=="Closest-Insertion")
    PlotArea.setC_I(points);
    PlotArea.repaint();
    pane2.add(run);

  • How to draw a line(shortest distance)  between two ellipse using SWING

    how to draw a line(should be shortest distance) between two ellipse using SWING
    any help will be appreciated
    regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ELine extends JPanel {
        Ellipse2D.Double red = new Ellipse2D.Double(150,110,75,165);
        Ellipse2D.Double blue = new Ellipse2D.Double(150,50,100,50);
        Line2D.Double line = new Line2D.Double();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.blue);
            g2.draw(blue);
            g2.setPaint(Color.red);
            g2.draw(red);
        private void connect() {
            double flatness = 0.01;
            PathIterator pit = blue.getPathIterator(null, flatness);
            double[] coords = new double[2];
            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        Point2D.Double p = getClosestPoint(coords[0], coords[1]);
                        double dist = p.distance(coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            x1 = coords[0];
                            y1 = coords[1];
                            x2 = p.x;
                            y2 = p.y;
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("blue type: " + type);
                pit.next();
            line.setLine(x1, y1, x2, y2);
        private Point2D.Double getClosestPoint(double x, double y) {
            double flatness = 0.01;
            PathIterator pit = red.getPathIterator(null, flatness);
            double[] coords = new double[2];
            Point2D.Double p = new Point2D.Double();
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        double dist = Point2D.distance(x, y, coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            p.setLocation(coords[0], coords[1]);
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("red type: " + type);
                pit.next();
            return p;
        public static void main(String[] args) {
            final ELine test = new ELine();
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Graphics g = test.getGraphics();
                    g.drawString("drag me", 175, 80);
                    g.dispose();
        private MouseInputAdapter mia = new MouseInputAdapter() {
            Point2D.Double offset = new Point2D.Double();
            boolean dragging = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(blue.contains(p)) {
                    offset.x = p.x - blue.x;
                    offset.y = p.y - blue.y;
                    dragging = true;
            public void mouseReleased(MouseEvent e) {
                dragging = false;
            public void mouseDragged(MouseEvent e) {
                if(dragging) {
                    double x = e.getX() - offset.x;
                    double y = e.getY() - offset.y;
                    blue.setFrame(x, y, blue.width, blue.height);
                    connect();
                    repaint();
    }

  • How to draw multiple lines on same panel??

    hiya
    i would like to know how can I draw multiple lines on the same panel ?? I have already use repaint(); but it just come out the lastest line (say line 3) i draw .......those previous lines(say line 1 and 2) are disappear ........
    Thanks for your help mate

    http://www.java2s.com/ExampleCode/2D-Graphics/Line.htm

  • How to draw horizontal line in smartform after end of the all line items

    Hi Friends,
    I am working on the smartform. I have created TABLE node in Main window.
    i want to draw a horizontal line after end of the main window table node. i mean after printing all the line items of the table, I need to print one horizontal line.
    Could you please help me how to resolve this issue.
    FYI: I tried with the below two options. But no use.
    1. desinged footer area in the table node of the main window.
    2. tried with uline and system symbols.
    please correct me if i am wrong. please explain in detail how to draw horizontal line after end of the main window table.
    this is very urgent.
    Thanks in advance
    Regards
    Raghu

    Hello Valter Oliveira,
    Thanks for your answer. But I need some more detail about blank line text. i.e thrid point.
    Could you please tell me how to insert blank line text.
    1 - in your table, create a line type with only one column, with the same width of the table
    2 - in table painter, create a line under the line type
    3 - insert a blank line text in the footer section with the line type you have created.

  • Can we draw multiple lines on a single CAShapeLayer?

    I want to draw multiple lines on a single layer of CAShapeLayer by UITouch. Is it possible?

    if they use the same appleID then you can do it at www.icloud.com

Maybe you are looking for

  • How do I play my TV shows on my iMac?

    How do I play my TV shows on my iMac?

  • Blackberry Z 10 car connection

    since upgrading to software release 10.2.1.2102, when I pair my phone with my Mercedes the phone pairs correctly. However, once the car is turned off, rep[airing will not happen. The only way to repair is to delete all info from the car and the phone

  • Formatting for mac and windows

    Is it possible to have mi iPod formatted for both mac and windows? If so, how can I do it? Thanks

  • Problems with Mail...

    Initially, the problem started when why wife said that her e-mails disappeared.  I looked at her screen and saw that there was a warning triangle next to the Mailboxes' Inbox in the upper left corner of the Mail app.  I thought it odd that there was

  • Coming back out of ssl when no long needed

    Hi People, I have a TOMCAT/JSP/SERVLET/STRUTS web application that I've protected the login pages using ssl.. My problem is when I've finished and no longer want to suffer the overhead of ssl, I can't seem to persuade it back to http. I've tried usin