Draw a line over a JLabel

Hello,
Does anyone know if there is a way to draw a line over a JLabel. The scenario is that I have a Jpanel that uses a Gridbaglayout and has an array of JLabels(to display images). I have the need to connect labels and to have the line draw over any labels that it intersects.
I know this can be done if you use the same graphics context to draw the image and the line, but since I need to use JLabels and the graphics context that draws the line is a JPanel's, I have a problem.
Is there a way to draw a line over a JLabel?
Thanks
lon

Easiest thing to do would be to override paintChildren like
public void paintChildren(Graphics g) {
  super.paintChildren(g);
  //paint your line here
}That should do what you want - paint the children first and then draw over them

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.

  • Is there a way to make keynote "draw" a line over a period of time.  In some cases I can "fake" it using a wipe but if the line double backs on itself, it is not what I would like.  Suggestions?  Enhancement request?

    I can fake what I need if the path is something like:
    But if the path doubles back on itself, such as:
    The wipe does not have the desired effect.  I would think the appropriate name for what I want would be "Draw".  I want the line to be drawn from one end to the other in a specified amount of time.

    create 2 draw shapes showing as a single coloured line;
    one that shows the line from the starting point at the left to the furthest point it extends to the right
    the second line starts from the end point of line 1 to the furthest  point it extends to the left
    add a wipe to line 1, wiping from left to right
    add a wipe to line 2, wiping from  right to left,  which automatically builds after build 1, with no delay
    when played back it will look like a single wipe

  • Drawing a straight line over a video

    Is it possible to draw a straight line over a video in CS6 and also to watch the video frame by frame to take exact timings?

    Hi Jeff,
    Back again! i have managed to put the line over the video and can have it on there as long or as short time as i wish, but it appears to be moving with the video and i need it to stay at a certain point and the video to carry on playing. Basically im trying to mark a point on a race track where the horse in the lead gets to, then i need the line to stay there for when the last horse comes to the line, with the lead horse moving on past. Currently the line doesnt stay on a specific point it on the video and go out of shot when the video moves, it appears to be moving with the video. I know the overlay is a static image but is there a way of making it look like it stays in a specific place on the video?
    Hope this makes sense!
    Thanks Kat

  • Draw line over Image??.. in Grid Format

    Hello frnds,
    what i want to do in my project is to draw image on JPanel with grid lines.. ??
    May be image in background and lines over image..
    I searched forum before but coulnt find appropriate thread.. please help me out??
    gervini

    from within the JPanel's paint() method.In Swing components you should overide the paintComponent() method, not paint().

  • Here are my last 3 duke dollars.  Can someone please help me draw a line?

    I have been BEATING my head on this for well over a week now. I'm new to Java2D and I cannot find even one example of this simple little thing that I am trying to do. Not one.
    All I want to do is draw an image, zoom that image, then draw some lines on that image, and then zoom it and have those lines show up where they should.
    For example, we have an image which has been zoomed. No lines are yet drawn on it.
    A line is added.
    The image is then zoomed in or out one more time.
    How do we get the line to remap to the newly zoomed image?
    What I am doing is:
    0) Load up an image from a file.
    1) Create a zoomed image by using the Image.getScaledInstance() method.
    2) Create a BufferedImage with the width and height of the image AFTER the zoom has taken place.
    3) Create a Graphics2D object by the createGraphics from this BufferedImage.
    4) Place the image into the BufferedImage by doing a BufferedImage.drawImage
    5) Select two points to be the start and end of the line.
    6) Draw the line using Graphics2D.drawLine(start.x, start.y, end.x, end.y).
    7) Zoom the image again (using the Image.getScaledInstance() method.
    8) Create a new ImageIcon using the image from above and override its paintIcon method like this:
    ImageIcon newIcon = new ImageIcon(newImage) {                       
    public void paintIcon(Component c, Graphics g, int x, int y)
    super.paintIcon(c, g, x, y);
    zoom(); //<---- ZOOM call
    Now in the zoom routine, what do I need to do to get the lines to draw at the proper location and size?
    Remember, the points of the lines (stored in a list as home grown line objects) are in screen coordinates, not image coordinates since they are just click points
    Note that when I use these points to draw a line, all is well (the line gets drawn where it should), but I have problems when I zoom the image.
    Thanks!

    Below is the documentation and method signature of
    Graphics.drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer);The important thing to note is that it does scaling on the fly if the size dictated by the source co-ordinates is defferent than the size dictated by the destination co-ordinates. The source image is always left un-touched.
    So basically your visual data is located in an offscreen image. You can draw a line on that. Then create a new image, get it's graphics and call drawImage(original_image, co-ordinates that cause it to scale how you like).
    Then you can draw lines on the 2nd image, create a 3rd, ...etc
         * Draws as much of the specified area of the specified image as is
         * currently available, scaling it on the fly to fit inside the
         * specified area of the destination drawable surface. Transparent pixels
         * do not affect whatever pixels are already there.
         * <p>
         * This method returns immediately in all cases, even if the
         * image area to be drawn has not yet been scaled, dithered, and converted
         * for the current output device.
         * If the current output representation is not yet complete then
         * <code>drawImage</code> returns <code>false</code>. As more of
         * the image becomes available, the process that draws the image notifies
         * the specified image observer.
         * <p>
         * This method always uses the unscaled version of the image
         * to render the scaled rectangle and performs the required
         * scaling on the fly. It does not use a cached, scaled version
         * of the image for this operation. Scaling of the image from source
         * to destination is performed such that the first coordinate
         * of the source rectangle is mapped to the first coordinate of
         * the destination rectangle, and the second source coordinate is
         * mapped to the second destination coordinate. The subimage is
         * scaled and flipped as needed to preserve those mappings.
         * @param       img the specified image to be drawn
         * @param       dx1 the <i>x</i> coordinate of the first corner of the
         *                    destination rectangle.
         * @param       dy1 the <i>y</i> coordinate of the first corner of the
         *                    destination rectangle.
         * @param       dx2 the <i>x</i> coordinate of the second corner of the
         *                    destination rectangle.
         * @param       dy2 the <i>y</i> coordinate of the second corner of the
         *                    destination rectangle.
         * @param       sx1 the <i>x</i> coordinate of the first corner of the
         *                    source rectangle.
         * @param       sy1 the <i>y</i> coordinate of the first corner of the
         *                    source rectangle.
         * @param       sx2 the <i>x</i> coordinate of the second corner of the
         *                    source rectangle.
         * @param       sy2 the <i>y</i> coordinate of the second corner of the
         *                    source rectangle.
         * @param       observer object to be notified as more of the image is
         *                    scaled and converted.
         * @return   <code>true</code> if the current output representation
         *           is complete; <code>false</code> otherwise.
         * @see         java.awt.Image
         * @see         java.awt.image.ImageObserver
         * @see         java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
         * @since       JDK1.1
        public abstract boolean drawImage(Image img,
                              int dx1, int dy1, int dx2, int dy2,
                              int sx1, int sy1, int sx2, int sy2,
                              ImageObserver observer);

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

    All,
    I have a program that draws simple lines using the Line2D class. As I draw the line, I bisect it to get a point in the middle of the line. Now I have 3 points on my line.
    From here I am trying to draw a short perpendicular line originating from my bisecting point.
    I have been attempting to work from the slope formula m = (x1 - x2) / (y1 - y2), but my trig skills have gotten rusty and I can't figure out how to draw a line from an existing point and a known slope. So I have been trying to just manipulate the rise over run by taking the negative inverse (-run/rise), and adding those values to my known point. But to no avail.
    Now that I'm frustrated, I'm wondering if I'm barking up the wrong tree. Should I be using Arcs and angles to determine my perpendicular point? Or, is there an easier way to draw lines from a known point and slope?
    Thanks in advance.

    Got it.
    I was thinking about the triangle from the wrong perspective. I was making my line the adjacent side of the triangle. Once I looked at it as the hypotenuse, I realized I already had the point I was looking for.
    Was right there all along. Doh.

  • 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

  • Draw a line it creates a path???

    Hi
    Just installed Fireworks 8 and everytime I draw a basic line
    it creates a path Im used to fireworks four so is this normal ?
    Surely it should just draw the line on the image and not
    create seperate paths for each one ..far as I know I never selected
    paths just the line tool ..any ideas ?

    If you really need to draw a plain, bitmap line, use the
    pencil tool. If
    you want more control over the style of your bitmap lines,
    use the brush
    tool. What you end up with one bitmap object with hundreds of
    "non-editable" lines, so you are not any further ahead, IMHO.
    Use the Line tool and name your lines in the Layers panel if
    you are
    concerned about not knowing which line is which. You can also
    group your
    lines to reduce the number of objects within the layers
    panel.
    There is also a connector line auto shape that might be
    useful for you.
    It's not as functional as connector objects within flowchart
    diagram
    programs like SmartDraw, but it's usable.
    Jim Babbage - .:Community MX:. & .:Adobe Community
    Expert:.
    Extending Knowledge, Daily
    http://www.communityMX.com/
    CommunityMX - Free Resources:
    http://www.communitymx.com/free.cfm
    .:Adobe Community Expert for Fireworks:.
    news://forums.macromedia.com/macromedia.fireworks
    news://forums.macromedia.com/macromedia.dreamweaver
    Alex Mariño wrote:
    > The advantages of having paths as opposed to bitmap
    lines are:
    >
    > 1. Smaller file size.
    > 2. Ease of further manipulation.
    >
    > alex
    >
    >
    >
    >
    >
    > crashpolo wrote:
    >> How do you draw a basic line then without creating a
    path ....say a
    >> black lien linking to rectangles together ?
    >>
    >> If i draw a large diagram with lines on it im gonn
    have hundreds of
    >> paths this cant be right can it ?
    >>

  • Draw a line at a threshold of high colour contrast

    Hello,
    I'm wanting to write a script where photoshop can analyse a photo and draw a line where there is a high contrast of adjacent pixels. So i'd need a pixel differentiating script (like magnetic wand) which preceeded a draw line script i guess.
    Example: A photo of white circles on a black background, where circles are drawn over the top of the white circles.  
    Any ideas?
    cheers

    Sounds like Illustrator's Live Trace feature…?

  • 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

  • How do I get the screen to refresh when drawing a line larger than the art board

    How do I get the screen to refresh properly when drawing a line larger than the art board when the screen scrolls? Everything turns white in CS6, CS5 and CS4.

    Existing art - not the new art.  The new art just gets a proxy shape - seen in my example as the blue rectangle.  The existing art is what gets smeared as you drag past the edge of the screen.  If it's anything other than an Ilustrator thing, it's a Mac thing. I've never known it to be any other way other than maybe in the past showing blank white instead of stuttered art on probably 10 different macs over the years.
    Take any art that you've ever created.  Zoom in so that your art is bigger than your screen (so that there's somewhere to scroll).  Rectangle tool (or move, scale, rotate(?) something, or draw a line) Start your rectangle anywhere, drag so that you are at the edge of the screen, causing it to scroll.  The existing art will get all effed up.  The rectangle you're drawing will draw as you expect it to - that's not the issue.
    How does Wade take his videos?

  • Custom Control Help: Draw a line and output start and end points

    I'm looking to find or make a custom control (or simple subVI) that will appear as a 100x100 unit grid and allow me to draw a line from one point to another on that grid. It will then output the (x,y) of the starting and end point of that line on the grid.  Any help or ideas?
    Thanks,
    Steve
    LabVIEW 2009 SP1
    Solved!
    Go to Solution.

    What you basically want is a loop with an event structure where you process Mouse Down, Move and Up events for your controls. There are any number of ways of implementing something like this, but this one will probably be the simplest:
    Use a multicolumn listbox or a table for your grid. Hide the scrollbars and headers.
    You can use the ActiveCell property with -2,-2 to select all cells. You can then use the cell size property to set the exact size of the cell.
    Next, you put a picture control on top of the table and color its background transparent so that the table shows through. You use property node to make sure the two are aligned to exactly the same spot and size.
    You use the mouse events on the picture control to detect the clicks and moves.
    You use the table's Point to Row Column method to translate the event's position data to a cell.
    You use the picture control VIs to draw the line on the picture based on that data.
    You can even color the selected cells in the table using the table properties.
    If you want to simplify things somewhat, you can also use the timeout event instead of the Mouse Move event to draw the line, but then you'll need to keep the timeout value in a shift register and reset it to -1 (no timeout) when the Mouse Up event happens.
    I would also suggest processing Mouse Enter and Leave events to change the cursor and cancel if the user leaves in the middle of dragging.
    Try to take over the world!

Maybe you are looking for

  • Missing files after upgrading to lr 2.3

    lr 1.4 starting acting odd a couple days ago when certain photos in certain folders when clicked on and viewed in the filmstrip mode suddently changed right in front of me. they were cting like the syn mode was stuck in +20 wb. as soon as the change

  • Totals not working correctly

    I am trying to create a calculation by evaluating a set of records and including only those that meet the criteria in the total. The calculation seems to work correctly on the individual records, but the total does not... it seems to be doubling the

  • Capture Change in historical data from ISU to BW

    Hi all, When any exceptions (EMMA, Work Item, Work Management Activity) are raised in our ISU system we assign it to different person so that they can start working on it and clear the exceptions. We have custom datasouce build around this process an

  • WLS 7.0.0.0 and clientgen from 7.0.0.1 & NoSuchFieldError

    I am trying to run the following code on one of our dev servers that is running WLS 7.0.0.0. I generated the Web Service client code using clientgen on my local machine using 7.0.0.1. The code is below (I marked the line where it chokes). // Setup th

  • Printing as PDF changes Doc?????

    Hey everyone, I have hit a wall and I need some serious help. I have a rather large word 2007 document with pictures, graphs, page breaks etc.. when I go to print and select print to PDF, like I normally do, it will give me the PDF file and it looks