我想在 Java 中创建一个简单的 Paint

I want to create a simple Paint in Java

提问人:Hưng Nguyễn Thành 提问时间:11/15/2023 最后编辑:camickrHưng Nguyễn Thành 更新时间:11/15/2023 访问量:115

问:

我想修改程序,将构成字母一笔的一系列点与直线连接起来,以便可以绘制单词,但我真的不知道该怎么做,所以我想要一些参考。我尝试使用 drawLine 绘制它们,但这不是我真正想要的。

https://i.stack.imgur.com/1MZpB.png

这是我的代码:

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);
    }
}
Java Swing Paint组件

评论

0赞 Hưng Nguyễn Thành 11/15/2023
好吧,我正在我的大学里学习这个,我确实了解 Swing 的基础知识,但我只是在这里连接点有问题。@davidalayachew
0赞 davidalayachew 11/15/2023
我现在意识到你问的问题与我所假设的截然不同。我现在正在输入您实际问题的答案。
0赞 davidalayachew 11/15/2023
也就是说,案文的措辞也不是很清楚。你真正想说的是,“我用这种方法试图画线,但我只得到了一堆线条形状的点,而不是实际的线条。我该如何把这些点连接起来?我鼓励你编辑你的问题,改为这样说。drawLine
0赞 Hưng Nguyễn Thành 11/15/2023
@davidalayachew哇,我非常感谢。是的,正如你所说,我仍然是大学一年级的学生,我对 Swing 仍然不够满意,尤其是对 Paint Component,但我必须为我的教授完成我的作业,所以我真的需要帮助。
0赞 Hưng Nguyễn Thành 11/15/2023
@davidalayachew啊,不不不,这是因为我编辑了问题。实际上,我还有另一个我写的代码,但因为我觉得那个代码比原来的代码更糟糕,所以我编辑了我的帖子。

答:

0赞 davidalayachew #1
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();
   
   }

}

在这种情况下,我们甚至不会创建您所做的任何点。我们所做的只是使用 ,然后将其添加到我们的 .我也把你改成了一个普通的.这样做会给我们带来 ,我刚刚用它来重置我们的并开始一个新的。必须跑,这样我回来后就可以回答问题。MouseEvent.getPoint()VectorMouseMotionAdapterMouseAdaptermouseMovedVector

评论

0赞 Hưng Nguyễn Thành 11/15/2023
嗯,它说 Vector<Point> 类型中的方法 add(Point) 不适用于参数 (java.awt.Point)。再想想,我想我的教授也会让我们保留课堂点。
0赞 Hưng Nguyễn Thành 11/15/2023
你能再次粘贴你的第一个答案吗?我想稍微研究一下。
0赞 Hưng Nguyễn Thành 11/15/2023
我已经像这样修复了我的代码,我认为它现在还可以,但它看起来仍然与示例有点不同,但我认为这可能接近我的教授要求,所以我只想发布以确认一点:
0赞 davidalayachew 11/18/2023
你好,对不起,我错过了你的问题。您还有未解决的请求吗?作为一个公平的警告,MadProgrammer 是 Swing 的专家之一,所以他们的答案会比我的答案高。
-1赞 Hưng Nguyễn Thành 11/15/2023 #2
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);
    }
}
3赞 MadProgrammer 11/15/2023 #3

拖动(多个形状)

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

连接线

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

断开的线路

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

一些注意事项

  • 不要用,用,你可能不会注意到它,但会更快VectorArrayListArrayList
  • 图形 2D API 已经有一个类,不要重新发明轮子Point
  • 面板用于绘制内容的“状态”信息应该与它相关(或通过某种模型提供)
  • paintComponent应该是,没有其他任何人可以称呼它protected