MouseEvent on JPanel - wrong coordinate

不打扰是莪最后的温柔 提交于 2019-12-01 18:46:28

I tried your code. I think your problem comes from the fact that you paint on the t3_aux1 using t3_aux2 coordinates. I'll try something to confirm that, and I come back here ...

EDIT: OK, that's it.

in t3_aux1 constructor, if you write

System.out.println("panel1 height = " + panel1.getHeight());
System.out.println("label1 height = " + label1_x.getHeight())

it prints

panel1 height = 42
label1 height = 20

So your offset is 42 + 20 + 4*2 = 70

4*2 comes from your lines borders with a thickness of 2.

Since it's possible to calculate the exact offset, you can dynamically fix it.

EDIT 2 :

In fact, the coordinates you uses come from panel2 since the mouseListener is attached to panel2. But you draw on the JFrame Graphics, not on panel2 graphics.

writing this should fix your coordinates problem.

inst2.paintComponent(panel2.getGraphics());

But as Kleopatra said, you're not doing it the right way. You should never call getGraphics() or paintComponent(). I think you should consider using java.awt.Canvas as a super class for your "panel2" object.

One more advice : Be aware that your drawings aren't memorized, so, if you reduce the window or hide it behind another one, everything drawn will be lost.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!