Draw the line on the Jpanel when dragging the mouse

你说的曾经没有我的故事 提交于 2019-11-29 12:03:25

..draw 2 lines

That seems like the crux of the matter in this question.

Keep a collection of lines in an expandable list (e.g. ArrayList) when clicking/dragging, add a new line to the list and call repaint(). In paintComponent(Graphics), iterate the collection and draw each line.

BTW - I am guessing you have not minimized and restored your window while testing this. Your lines (beautiful or ugly) would disappear!


..they disappeared. What's the reason?

The methods paint() and paintComponent() are called whenever the GUI needs to redraw. They might be invoked after another window appears in front of the app., then it is brought back to the front. Another time is after being restored from minimized.

The options to retain the lines include:

  • Store the locations of the line(s) and redraw all of them whenever asked (as described above). This can work for most purposes. Even if there are hundreds of lines, the GUI will redraw them in 'the blink of an eye'.
  • Draw each line to a BufferedImage and put the image in (an ImageIcon in) a JLabel. This approach works well if the drawing area is of a fixed size & nothing is ever removed, and can accommodate ..millions of lines, arcs, semi-transparent areas, smaller images, text.. Using an image as a rendering surface, you would no longer need the ArrayList, since all you do is add a new line to the image, and repaint the label to see the new line and all previous lines.

..the line is not the straight line.

That is because of the 'rendering hints' used when drawing the line. A screen made of aligned rows of pixels can only make vertical or horizontal lines perfectly. To give the 'illusion' of a straight & continuous line at any other angle, requires a technique known as dithering. Read the opening sections of Graphics2D for more explanation and description of the RenderingHints.

I don't know I get your question, but if you want to draw a continuous line. When dragging you have to update your last point possition.

@Override
  public void mouseDragged(MouseEvent e) {
    point2 = e.getPoint();
    line2d = new Line2D.Double(point1, point2); 
    point1 = point2;  // add this line
    repaint();
  }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!