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);
}

Similar Messages

  • 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 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 to Draw a line Graph using x,y Cordinates in Java ?

    Hi,
    what r the easiest way to draw a line Graph using Java Code either applet.
    can u give me code sample. or any package where we can pass some parameter so that accoring to the paramter as i know jfreeChart.function() like some method is there from toold jChart.
    Is it possible.
    Regards,
    Prabhat

    There's a number of sample applications in one of the packages of freechart, one of which should do the trick.
    If you're doing applets I suggest you look at genjar from the sourceforge site. What that does is bundle classes from a set of library jars into one jar, selecting only classes that are referenced. That should simplify the transfer problem.
    To draw graphs, typically, you create a DefaultXYDataset object, add data points and then use the appropriate ChartFactory.createXXX methods to build a chart object. Then you wrap that in a ChartPanel to display.

  • 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);

  • 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

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

  • Creating a drawing (CAD) program in Java

    I'm in the planning stages of creating a drawing/drafting program in Java, and I'm fairly new to Swing, so I need some guidance.
    For a drafting program, I will need to be able to draw all kinds of objects using lines, curves, etc, connected in various ways. One thing I could do is extend JComponent and override the paint() method, and have it put up all the various objects as it repaints. The problem with this is that if a user clicks on an object, how will I detect which object he clicked on? I'll get mouse coordinates, but then how do I go from that to knowing that he clicked on a certain curve, etc?
    The alternative is to not extend JComponent, but rather to make each of the individual objects on the screen its own component and then lay them out using absolute positioning. Then I'll get mouse events as the user clicks on things. Is this a better way to do it? And if so, I guess I'll still need to create individual components that represent lines, arcs, curves, etc?
    Swing has so many features that it's hard for a beginning to get started into it. Thanks for any tips.

    Personally I wouldn't work with Swing for this functionality,
    but I would rather work with java 2D instead.
    Swing contains to much overhead for the kind of application you plan to develop.
    Look for the java.awt.Shape interface and to the java.awt.geom.* implementations of such shapes.
    It contains already most of the functionality required for painting and hit-detection of a shape on the
    screen.
    kind regards,

  • Displaying Lines in java Qusetion?

    hi,
    i was wondering is there a way to display thick 2d lines in java swing when drawing lines with paintComponent(). the default is very thin but i was wondering is there a method to display wider lines!!
    cheers in advance

    You can define line width using setStroke(Stroke myStroke) of Graphics2D class.
    Cheers
    DB

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

  • Drawing dotted lines

    Hey
    I've already figured out how to draw dotted lines so that's not the questions
    the thing is I only need to draw some lines as dotted, some as dashed and all others just normal..
    I figured I could make radiobox to select which line.. then I save that to an array of some sort and then in the paintComponent thing I should make an if to check for array value and change the stoke according to that
    so far I've just made my lines dotted like this
    http://www.jguru.com/faq/view.jsp?EID=114099
    but now everything is dotted.. even the borders around my buttons..
    ni my applet I have some buttons which are connected with a line.. I want that line dotted or dashed when the users wants it to.. and only then otherwise just normal lines
    I couldn't find anything about that on the google =(

    done!
    now I want to be able to use diffrent line style combinations but it doesn't work
    currently it only uses the linestyle that you selected for the first line and then uses that for every line after that too
    this is my code
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setColor(lijnKleur);
              for (int i = 0; i < Main.XList.size(); i++) {
                   int j = (i - 1);
                   int k = (i + 1);
                   int aantal = 0;
                   if ((k % 2 == 0) && (i != 0)) {
                        if (Main.lijnstyleList.get(aantal) == 1){
                             g2d.setStroke(normaal);
                        else if (Main.lijnstyleList.get(aantal) == 2){
                             g2d.setStroke(gestippeld);
                        else if (Main.lijnstyleList.get(aantal) == 3){
                             g2d.setStroke(gestreept);
                        else{
                             g2d.setStroke(normaal);
                        int tmpX_oud = Main.XList.get(j) + (Main.breedte / 2);
                        int tmpY_oud = Main.YList.get(j) + (Main.hoogte / 2);
                        int tmpX = Main.XList.get(i) + (Main.breedte / 2);
                        int tmpY = Main.YList.get(i) + (Main.hoogte / 2);
                        aantal++;
                        if (tmpY_oud > tmpY){
                             tmpY = tmpY + (Main.hoogte / 2);
                             int half = tmpY + (Main.spacing / 2);
                             if ((tmpY_oud != tmpY) && (tmpX_oud != tmpX)) {
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX_oud, half);
                                  g2d.drawLine(tmpX_oud, half, tmpX, half);
                                  g2d.drawLine(tmpX, half, tmpX, tmpY);
                             else{
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX, tmpY);
                             g2d.drawLine(tmpX, tmpY, tmpX - 5, tmpY + 8);
                             g2d.drawLine(tmpX, tmpY, tmpX + 5, tmpY + 8);
                        else if (tmpY_oud < tmpY){
                             tmpY = tmpY - (Main.hoogte / 2);
                             int half = tmpY - (Main.spacing / 2);
                             if ((tmpY_oud != tmpY) && (tmpX_oud != tmpX)) {
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX_oud, half);
                                  g2d.drawLine(tmpX_oud, half, tmpX, half);
                                  g2d.drawLine(tmpX, half, tmpX, tmpY);     
                             else{
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX, tmpY);
                             g2d.drawLine(tmpX, tmpY, tmpX - 5, tmpY - 8);
                             g2d.drawLine(tmpX, tmpY, tmpX + 5, tmpY - 8);
                        else {
                             if (tmpX_oud > tmpX){
                                  tmpX = tmpX + (Main.breedte / 2);
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX, tmpY);
                                  g2d.drawLine(tmpX, tmpY, tmpX + 8, tmpY - 5);
                                  g2d.drawLine(tmpX, tmpY, tmpX + 8, tmpY + 5);
                             else{
                                  tmpX = tmpX - (Main.breedte / 2);
                                  g2d.drawLine(tmpX_oud, tmpY_oud, tmpX, tmpY);
                                  g2d.drawLine(tmpX, tmpY, tmpX - 8, tmpY - 5);
                                  g2d.drawLine(tmpX, tmpY, tmpX - 8, tmpY + 5);
              g2d.setStroke(normaal);
         }**EDIT**
    according to this it can be done..
    http://java.sun.com/developer/JDCTechTips/2003/tt0520.htm
    no clue why mine doesn't work then
    Edited by: Nizzle on Sep 13, 2007 10:15 AM

  • Draw a line smoothed

    How can I draw a line smoothed with awt.graphics???
    I use this class and not Java 2D because i need use it with I.E. without Java Plugin.

    there are quite a few line antialiasing algorithms out there. try for example http://graphics.lcs.mit.edu/classes/6.837/F01/Lecture05/Slide12h.html
    but any good computer graphics book will help.

  • "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 draw a line after i load a frame?

    its simple to draw a line before i load the frame..
    when i try to draw a line after i load the frame, i get a error in the last line of the lauchFrame method..
    the error is "java.awt.Graphics is abstract; cannot be instantiated"
    import java.awt.*;
    class GraphArea extends Panel
        public void paint(Graphics g)
            g.setColor(Color.BLUE);
            g.drawLine(0,0,250,250);
        public void paint(Graphics g,int X1, int X2)
            g.drawLine(0,0,X1,X2);
    class Grapherv1 {
      private Frame f;
      private GraphArea drawPanel;
      public Grapherv1() {
        f = new Frame("Drawing Shapes:Lenin");
        drawPanel = new GraphArea();
      public void launchFrame() {
          f.setLayout(new FlowLayout());
          drawPanel.setSize(950,550);
          drawPanel.setBackground(new Color(220,220,220));
          drawPanel.setLayout(null);
         f.setBackground(Color.white);
          f.add(drawPanel);
        f.pack();
        f.setSize(1000, 800);
        f.setVisible(true);
        drawPanel.paint(new Graphics(),100,100);
    public static void main(String args[]) throws InterruptedException {
          Grapherv1 gui = new Grapherv1();
        gui.launchFrame();
    }please tell me how to call this method ...
    public void paint(Graphics g,int X1, int X2)
    what argument i should pass for Graphics??
    Edited by: Tall-Dude on Dec 3, 2007 4:33 PM
    Edited by: Tall-Dude on Dec 3, 2007 4:33 PM

    Tall-Dude wrote:
    please tell me how to call this method ...
    public void paint(Graphics g,int X1, int X2)just past the new x1 and x2 and repaint no need to pass the graphics.
    e.g.
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    class Grapherv1 {
        private Frame f;
        private GraphArea drawPanel;
        public Grapherv1() {
            f = new Frame("Drawing Shapes:Lenin");
            drawPanel = new GraphArea();
        public void launchFrame() {
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            f.setLayout(new BorderLayout());
            drawPanel.setSize(950,550);
            drawPanel.setBackground(new Color(220,220,220));
            drawPanel.setLayout(null);
            f.setBackground(Color.white);
            f.add(drawPanel);
            f.pack();
            f.setSize(1000, 800);
            f.setVisible(true);
            drawPanel.redraw(300,400);
        public static void main(String args[]) throws InterruptedException {
            Grapherv1 gui = new Grapherv1();
            gui.launchFrame();
        class GraphArea extends Panel {
            int x1, x2;
            public void paint(Graphics g) {
                g.setColor(Color.BLUE);
                g.drawLine(0,0,x1,x2);
            public void redraw(int X1, int X2) {
                x1 = X1;
                x2 = X2;
                repaint();
    }

Maybe you are looking for