有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线在未最大化时绘制在错误的位置

我扩展了JPanel并重写了paint方法,以便在面板中某些JButton的位置之间绘制一些额外的线。但是,只有当gui最大化时,才会正确绘制线条,否则它们将以完全错误的偏移量绘制

要绘制我正在使用的行('rootNode'和'child'都是JButtong是重写的paint方法的Graphics参数):

Point sourcePoint = new Point(rootNode.getLocation());
Point destPoint = new Point(child.getLocation());
SwingUtilities.convertPointToScreen(sourcePoint, rootNode.getParent());
SwingUtilities.convertPointToScreen(destPoint, child.getParent());
g.drawLine(sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y);

未最大化时错误行的图片:http://postimage.org/image/ws0yo9chf/ 最大化时正确的图片:http://postimage.org/image/fq84m5xmb/


共 (1) 个答案

  1. # 1 楼答案

    只是为了掩盖这些评论。我认为在这种情况下你不想转换成屏幕坐标

    paintComponent(...)方法的Graphics上下文很可能是为组件坐标系设置的

    JavaDoc for Graphics.drawLine(...)声明:

    Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.

    除非您通过Graphics.translate(...)Graphics2D.setTransform(...)对其进行了更改,否则将为组件设置坐标系

    除了位于错误的位置之外,转换为屏幕坐标还会根据窗口在屏幕上的位置改变线条的位置:)