使用JPanel绘制直线并获取点坐标 [英] Using JPanel to draw straight lines and get point coordinates
问题描述
我现在全神贯注.我在用Java构建GUI方面工作不多,我一直在阅读关于swing和JPanel的所有文章,我认为我想做的事情是可能的,只是我还没弄清楚怎么做
I am at a total loss right now. I haven't worked much with building GUIs in Java, I've been reading all about swing and JPanel, and I think what I am trying to do is possible, I just haven't figured out how.
我正在尝试构建一个GUI,您可以在其中在特定绘图区域内绘制直线,我希望能够获取起点/终点坐标,以便对这些点进行一些数学运算.任何帮助将不胜感激!
I'm trying to build a GUI in which you can draw straight lines within a certain drawing area, I would like to be able to get the start/endpoint coordinates in order to perform some math with those points. Any help would be greatly appreciated!
推荐答案
我将代码留给您,因此这里是算法:
1.创建JFrame
并向其中添加JPanel
.
2.为JPanel
添加鼠标侦听器
3.每次按下鼠标,都获得单击的x和y. (起点)
4.拖动鼠标时,连续记录x和y.
5.释放鼠标时,记录x和y. (终点)
6.您可以使用Graphics
类的drawLine()
方法,也可以使用Graphics2D
的draw()
,在这种情况下,您将需要一个Line2D.Double
–参数保持不变-开始x,开始y,结束x和y端
这是一张更好地解释律的图片:
I will leave the code to you so here is the algorithm:
1. Create a JFrame
and add a JPanel
to it.
2. Add a mouse listener for the JPanel
3. Every time the mouse is pressed, get the x and y of the click. (starting points)
4. When the mouse is dragged , record x and y continuously.
5. When mouse is released, record the x and y. (ending points)
6. You could either use the drawLine()
method of Graphics
class or use draw()
of Graphics2D
in this case you will need a Line2D.Double
-- the arguments remain the same - start x, start y, end x and end y
here is an image to explain a lil bit better:
这篇关于使用JPanel绘制直线并获取点坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!