(上图来自AutoCAD)
我的应用程序使用两个Point类变量在JPanel上绘制一条线:" startPoint"和" finishPoint"。
"的startPoint"从第一次鼠标单击设置。一旦建立起始点,就在光标位置上设置finishPoint变量。因此,线条随着鼠标移动动态移动/增长,直到" finishPoint"通过第二次鼠标点击确定。
在建立startPoint且线条动态变化的时间段内,我想将JTextField定位在线条中点(如果可能的话,稍微偏离中心,以免它遮挡线条) ?
我知道如果我在不使用布局管理器的情况下尝试定位组件,我会大声嚷嚷,但我无法看到布局管理器如何提供帮助。我想使用坐标来定位JTextField。我能想到的唯一方法是以某种方式将文本字段添加到形状中。除此之外,我不知所措。
有人能让我朝着正确的方向前进吗?
我的代码应该有人想看到它:
package Drawing;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* An extension to P2PLines. A line from point A to point B but with an animation.
*/
public class LineAnimation extends JPanel implements MouseListener, MouseMotionListener
{
private Graphics g;
private Point lineStart = new Point(0, 0);
private Point lineFinish = new Point(0, 0);
private boolean drawing;
int globalX = 0, globalY;
ArrayList<Line2D> edges = new ArrayList<>();
public LineAnimation()
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
drawing = false;
}
@Override public void mouseClicked(MouseEvent me) {}
@Override public void mousePressed(MouseEvent me)
{
if (drawing)
{
g = getGraphics(); // Get Graphics content
g.setColor(Color.black);
lineFinish.move(me.getX(), me.getY());
g.drawLine(lineStart.x, lineStart.y, me.getX(), me.getY());
edges.add(new Line2D.Float(lineStart.x, lineStart.y, lineFinish.x, lineFinish.y));
drawing = false;
g.dispose();
}
else
{
lineStart.move(me.getX(), me.getY());
drawing = true;
}
}
@Override public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawPreviousLine((Graphics2D)g);
if (drawing)
{g.drawLine(lineStart.x, lineStart.y, globalX, globalY);}
}
private void drawPreviousLine(Graphics2D g)
{
for(Line2D lines: edges)
{g.draw(lines);}
}
@Override
public void mouseMoved(MouseEvent me)
{
repaint();
globalX = me.getX();
globalY = me.getY();
}
@Override public void mouseReleased(MouseEvent me) {}
@Override public void mouseEntered(MouseEvent me) {}
@Override public void mouseExited(MouseEvent me) {}
@Override public void mouseDragged(MouseEvent me) {}
public static void main(String[] args)
{
JFrame frame = new JFrame("Drawing Frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
LineAnimation drawingFrame = new LineAnimation();
frame.add(drawingFrame);
frame.setVisible(true);
drawingFrame.addMouseListener(drawingFrame);
drawingFrame.addMouseMotionListener(drawingFrame);
}
}