更新时间:2023-02-03 11:54:04
好的,我遇到了三个问题.
Okay, I've come across three issues.
首先:图像窗格上没有布局管理器.没什么大不了的,但是如果您不打算使用布局管理器,则您有责任对所有子组件进行布局.我通过将以下内容添加到"myObjet"类中来修复了该错误(错误的位置).
Firstly: There's no layout manager on the image pane. No big deal, but if you're not going to use a layout manager, you become responsible for laying out any child components. I fixed this (and it's in the wrong place) by adding the following to the "myObjet" class.
Dimension size = getPreferredSize();
setBounds(0, 0, size.width, size.height);
JImagePanel实际上应该解决这个问题-添加布局管理器或检查doLayout方法.
This really should be taken care of by the JImagePanel - either add a layout manager or check the doLayout method.
其次:JImagePanel是一个重量级的组件.如果可能的话,应避免混合重组分和轻组分(除其他外,还有Z顺序问题).我更新了JImagePanel以从JPanel扩展.
Secondly: The JImagePanel is a heavy weight component. You should avoid mixing heavy and light weight components if you can (there are Z order issues amongst other things). I updated the JImagePanel to extend from a JPanel.
第三,您应该很少需要重写paint方法.在您的情况下,我可以理解您为什么这样做,但是最终要做的是在所有其他事物的顶部进行绘画(并与您正在使用较重的分量的事实混合在一起,使问题更加复杂).
Thridly: You should only very rarely have to override the paint method. In your case I can understand why you did, but what you ended up doing was painting on the top of everything else (and mixed with the fact you were using a heavy weight component compounded the issue).
我将"paint"更改为"paintComponent",以绘制背景并能够使其正常工作.我能够四处移动图像,并将"myObjet"可见并固定在适当的位置.
I changed the "paint" for "paintComponent" which paints the background and was able to get it to work nicely. I was able to move the image around and have the "myObjet" visible and static in place.
更新
好吧...
public void mouseDragged(MouseEvent e) {
transX += e.getX() - MouseX;
transY += e.getY() - MouseY;
MouseX = e.getX();
MouseY = e.getY();
// Add this to your code
for (Component comp : getComponents()) {
comp.setLocation(transX, transY);
}
repaint();
}
实际上,更好的解决方案是允许父容器处理移动并在图像窗格中静态设置图像和对象(我的窗格设置为静态大小).您在这里运行的基本思想只需要移到容器中即可.
In fact, a better solution would be to allow the parent container to handle the movement and set the image and objects statically with in the image pane (my pane was set to a static size). The basic idea you have running here just needs to be moved to the container.
您需要处理的唯一另一件事是窗格的Z顺序.
The only other thing you would need to deal with is the Z order of the panes.