1

I want to modify the program to connect the series of dots that make up one stroke of a letter with a straight line so that words can be drawn but i don't really have a idea of how to do it so i want some references. I tried to draw them using drawLine but it's not what i really wanted.

https://i.sstatic.net/1MZpB.png

This is my code:

package tool;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

}

public class MyPaintApp extends JFrame {
    int x, y;
    Vector<Point> list = new Vector<>();

    class MyPanel extends JPanel {
        public MyPanel() {
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent event) {
                    x = event.getX();
                    y = event.getY();
                    list.add(new Point(x, y));
                    repaint();
                }
            });
        }

        public void paintComponent(Graphics g) {

            super.paintComponent(g);
            for (Point p : list)
                g.fillOval(p.x, p.y, 4, 4);
        }
    }

    public MyPaintApp() {
        setSize(600, 450);
        setLocation(400, 0);
        setTitle("My Paint");
        add(new MyPanel());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

}

public class MyPaintApp extends JFrame {
    int x, y;
    Vector<Point> list = new Vector<>();
    Vector<Vector<Point>> list1 = new Vector<>();

    class MyPanel extends JPanel {
        public MyPanel() {
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent event) {
                    x = event.getX();
                    y = event.getY();
                    list.add(new Point(x, y));
                    repaint();
                }
            });
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0; i < list.size() - 1; i++) {
                Point p1 = list.get(i);
                Point p2 = list.get(i + 1);
                g.drawLine(p1.x, p1.y, p2.x, p2.y);  
            }
        }
    }

    public MyPaintApp() {
        setSize(600, 450);
        setLocation(400, 0);
        setTitle("My Paint");
        add(new MyPanel());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
27
  • Well, I'm studying this in my University and i do understand the basics of Swing but i just have problem with connecting the dots here. @davidalayachew Commented Nov 15, 2023 at 2:14
  • I realize now that you were asking a wildly different question than what I had assumed. I am typing up an answer to your actual question now. Commented Nov 15, 2023 at 2:23
  • That said, the wording of the text is not very clear either. What you are really trying to say is that "I used the method drawLine to attempt to draw lines, but I only got a bunch of dots in the shape of a line instead of actual lines. How do I connect the dots?" I would encourage you to edit your question to say that instead. Commented Nov 15, 2023 at 2:24
  • @davidalayachew Wow, i appreciate it a lot. Yeah, as you said, I'm still a first year Uni student and I'm still not comfortable enough with Swing, specially with Paint Component but i have to finish my assignment for my professor so i really do need help. Commented Nov 15, 2023 at 2:26
  • @davidalayachew Ah, no no, this is because i edited to question. Actually i have another code that i wrote but because i feel like that one is even worse than the original so i edited my post. Commented Nov 15, 2023 at 2:27

3 Answers 3

3

Drag (multiple shapes)

enter image description here

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MyPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    class MyPanel extends JPanel {
        private List<List<Point>> shapes = new ArrayList<>(8);
        private List<Point> currentShape;

        public MyPanel() {
            MouseAdapter handler = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    currentShape = new ArrayList<>(64);
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    shapes.add(currentShape);
                    currentShape = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    currentShape.add(new Point(e.getX(), e.getY()));
                    repaint();
                }
            };

            addMouseMotionListener(handler);
            addMouseListener(handler);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();
            super.paintComponent(g2d);
            for (List<Point> shape : shapes) {
                paintShape(shape, g2d);
            }
            if (currentShape != null) {
                paintShape(currentShape, g2d);
            }
            g2d.dispose();
        }

        protected void paintShape(List<Point> shape, Graphics2D g2d) {
            Point from = null;
            for (Point p : shape) {
                Point to = p;
                if (from != null) {
                    g2d.drawLine(from.x, from.y, to.x, to.y);
                }
                from = to;
            }
        }
    }
}

Connected lines

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MyPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    class MyPanel extends JPanel {
        private List<Line2D> lines = new ArrayList<>(8);
        private Line2D nextLine;

        public MyPanel() {
            MouseAdapter handler = new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (nextLine != null) {
                        lines.add(nextLine);
                    }
                    nextLine = new Line2D.Double(e.getPoint(), e.getPoint());
                    repaint();
                }

                @Override
                public void mouseMoved(MouseEvent e) {
                    if (nextLine == null) {
                        return;
                    }
                    nextLine.setLine(nextLine.getP1(), e.getPoint());
                    repaint();
                }
            };

            addMouseListener(handler);
            addMouseMotionListener(handler);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();
            super.paintComponent(g2d);
            for (Line2D line : lines) {
                g2d.draw(line);
            }
            if (nextLine != null) {
                g2d.setColor(Color.RED);
                g2d.draw(nextLine);
            }
            g2d.dispose();
        }

        protected void paintShape(List<Point> shape, Graphics2D g2d) {
            Point from = null;
            for (Point p : shape) {
                Point to = p;
                if (from != null) {
                    g2d.drawLine(from.x, from.y, to.x, to.y);
                }
                from = to;
            }
        }
    }
}

Disconnected lines

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MyPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    class MyPanel extends JPanel {
        private List<Line2D> lines = new ArrayList<>(8);
        private Line2D nextLine;

        public MyPanel() {
            MouseAdapter handler = new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (nextLine != null) {
                        lines.add(nextLine);
                        nextLine = null;
                    } else {
                        nextLine = new Line2D.Double(e.getPoint(), e.getPoint());
                    }
                    repaint();
                }

                @Override
                public void mouseMoved(MouseEvent e) {
                    if (nextLine == null) {
                        return;
                    }
                    nextLine.setLine(nextLine.getP1(), e.getPoint());
                    repaint();
                }
            };

            addMouseListener(handler);
            addMouseMotionListener(handler);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();
            super.paintComponent(g2d);
            for (Line2D line : lines) {
                g2d.draw(line);
            }
            if (nextLine != null) {
                g2d.setColor(Color.RED);
                g2d.draw(nextLine);
            }
            g2d.dispose();
        }

        protected void paintShape(List<Point> shape, Graphics2D g2d) {
            Point from = null;
            for (Point p : shape) {
                Point to = p;
                if (from != null) {
                    g2d.drawLine(from.x, from.y, to.x, to.y);
                }
                from = to;
            }
        }
    }
}

Some notes

  • Don't use Vector, use ArrayList, you probably won't notice it, but ArrayList will be faster
  • The Graphics 2D API already has a Point class, don't re-invent the wheel
  • The "state" information the panel uses to paint the contents should be relative to it (or provide via some kind of model)
  • paintComponent should be protected, there's no reason for anyone else to be calling it
0
import java.util.Vector;
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;


public class MyPaintApp extends JFrame {
   Vector<Point> list = new Vector<>();
   Vector<Vector<Point>> list1 = new Vector<>();

   class MyPanel extends JPanel {
      public MyPanel() {
      
         final MouseAdapter mouseAdapter =
            new MouseAdapter() {
               public void mouseDragged(MouseEvent event) {
                  repaint();
                  list.add(event.getPoint());
               }
               public void mouseMoved(MouseEvent event) {
                  repaint();
               }
               public void mouseReleased(MouseEvent event) {
                  if (list.isEmpty()){
                     return;
                  }
               
                  list1.add(list);
                  list = new Vector<>();
                  repaint();
               }
            }
            ;
      
         this.addMouseMotionListener(mouseAdapter);
         this.addMouseListener(mouseAdapter);
      }
   
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         for (final Vector<Point> listA : list1) {
            for (int i = 0; i < listA.size() - 1; i++) {
               Point p1 = listA.get(i);
               Point p2 = listA.get(i + 1);
               g.drawLine(p1.x, p1.y, p2.x, p2.y);
            }
         }
      }
   }

   @SuppressWarnings("this-escape")
   public MyPaintApp() {
      setSize(600, 450);
      setLocation(400, 0);
      setTitle("My Paint");
      add(new MyPanel());
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

   public static void main(String[] args)
   {
   
      new MyPaintApp();
   
   }

}

In this case, we don't even create any of the dots that you did. All we did is grab the point from the event using MouseEvent.getPoint(), then add it to our Vector. I also changed your MouseMotionAdapter to just be a plain MouseAdapter. Doing so gives us the mouseMoved, which I just used to reset our Vector and start a new one. Have to run, so I can answer questions when I get back.

4
  • Hmm, it says something like the method add(Point) in the type Vector<Point> is not applicable for the arguments (java.awt.Point). And as a second thought, i think my professor will make us keep the class Point too i think. Commented Nov 15, 2023 at 5:27
  • Can you paste your first answer again? I want to look into it a little bit. Commented Nov 15, 2023 at 6:12
  • I have fixed my code like this and I think it's quite ok now but it still looks a bit different from the example, but i think this might be close what my prof requested so I just want to post to confirm a little bit: Commented Nov 15, 2023 at 8:59
  • Hello, sorry I missed your questions. Do you still have unresolved requests? As a fair warning, MadProgrammer is one of the experts on Swing, so their answer will by higher quaality than mine. Commented Nov 18, 2023 at 1:10
-1
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

}

public class MyPaintApp extends JFrame {
    int x, y;
    Vector<Point> list = new Vector<>();
    boolean isMousePressed = false;

    class MyPanel extends JPanel {
        public MyPanel() {
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent event) {
                    isMousePressed = true;
                    x = event.getX();
                    y = event.getY();
                    list.add(new Point(x, y));
                }
                
                public void mouseReleased(MouseEvent event) {
                    isMousePressed = false;
                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent event) {
                    if(isMousePressed) {
                    x = event.getX();
                    y = event.getY();
                    list.add(new Point(x, y));
                    repaint();
                    }
                }
                public void mouseMoved(MouseEvent event) {
                    if(isMousePressed) {
                    x = event.getX();
                    y = event.getY();
                    list.add(new Point(x, y));
                    repaint();
                    }
                }
            });
            
        }

        public void paintComponent(Graphics g) {

            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            g2d.setStroke(new BasicStroke(2.0f)); 
            for (Point p : list)
                g.fillOval(p.x, p.y, 4, 4);
        }
    }

    public MyPaintApp() {
        setSize(600, 450);
        setLocation(400, 0);
        setTitle("My Paint");
        add(new MyPanel());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.