2

我现在完全不知所措。我在 Java 中构建 GUI 的工作不多,我一直在阅读有关 Swing 和 JPanel 的所有内容,我认为我正在尝试做的事情是可能的,我只是还没弄清楚如何.

我正在尝试构建一个 GUI,您可以在其中绘制特定绘图区域内的直线,我希望能够获取起点/终点坐标,以便对这些点执行一些数学运算。任何帮助将不胜感激!

4

4 回答 4

11

我会把代码留给你,所以这里是算法:
1. 创建一个JFrame并添加一个JPanel
2.添加鼠标监听器JPanel
3.每次鼠标按下,获取点击的x和y。(起点)
4. 拖动鼠标时,连续记录x和y。
5. 松开鼠标后,记录 x 和 y。(结束点)
6. 您可以使用 class 的drawLine()方法Graphics或使用draw()Graphics2D这种情况下,您将需要 a Line2D.Double- 参数保持不变 - start x,start y,end x 和 end y



这是一张可以更好地解释 lil 的图片: 在此处输入图像描述

于 2013-02-17T07:21:32.867 回答
3

Start with Performing Custom Painting and 2D Graphics.

Basically, you going to need a mouse listener to monitor the user interaction with your panel, check out How to write mouse listeners for more infor still.

Depending on your needs, if you need to maintain all the click points of the user, you would need to store them in something like a List, or if you just need to know the start and end points, the you just need a couple of Point objects.

You would be able to use these to paint onto your surface and performing your required calculations.

Remember, in this context, the points are contextual to the container they were generated on. That is 0x0 will be the top left of the container

Updated

You could also take advantage of the Shape API, using a Line2D to represent the two points. This would make it easier to distinguish between distinct lines/points

于 2013-02-17T07:06:06.803 回答
1

you need to add the mouse listener on JPanel.

then:

public void mouseClicked(MouseEvent me){
if(click==1){
int x1=me.getX();
int y1=me.getY();
click=click+1;
}
else{
int x2=me.getX();
int y2=me.getY();
click=1;
}
}


drawLine(x1,y1,x2,y2)

To draw line with mouse move you can also add mouse motion listener.

于 2013-02-17T07:07:23.940 回答
1

这比“用 (x1,y1) 和 (x2, y2) 画直线”方法更难。

您需要一个Line(您的自定义)对象,该对象是动态创建并放置在JPanel正在侦听MouseEvents 的画布区域JPanel本身的。您还需要将 MODEL 与 VIEW 分开,以便您的自定义画布JPanel可以正确绘制自己并覆盖paintComponent()

这个问题有点模糊,所以我不能提供任何代码。

于 2013-02-17T07:03:56.277 回答