java线在未最大化时绘制在错误的位置
我扩展了JPanel
并重写了paint
方法,以便在面板中某些JButton
的位置之间绘制一些额外的线。但是,只有当gui最大化时,才会正确绘制线条,否则它们将以完全错误的偏移量绘制
要绘制我正在使用的行('rootNode'和'child'都是JButton
,g
是重写的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 楼答案
只是为了掩盖这些评论。我认为在这种情况下你不想转换成屏幕坐标
paintComponent(...)
方法的Graphics
上下文很可能是为组件坐标系设置的JavaDoc for
Graphics.drawLine(...)
声明:除非您通过
Graphics.translate(...)
或Graphics2D.setTransform(...)
对其进行了更改,否则将为组件设置坐标系除了位于错误的位置之外,转换为屏幕坐标还会根据窗口在屏幕上的位置改变线条的位置:)