在JScrollPane内的JPanel上绘画无法在正确的位置绘画 [英] Painting on a JPanel inside a JScrollPane doesn't paint in the right location
问题描述
所以我在JScrollPane
内有一个JPanel
.
现在,我试图在面板上画一些东西,但是总是在同一位置.
我可以向各个方向滚动,但不会移动.我在面板上绘制的所有内容都不会滚动.
So I have a JPanel
that's inside a JScrollPane
.
Now I am trying to paint something on the panel, but it's always in same spot.
I can scroll in all directions but it's not moving. Whatever I paint on the panel does not get scrolled.
我已经尝试过:
- 自定义
JViewPort
- 在Opaque = true和Opaque = false之间切换
我还考虑了覆盖面板的paintComponent
方法,但这在我的代码中将很难实现.
Also I considered overriding the paintComponent
method of the panel but that would be really hard to implement in my code.
public class ScrollPanePaint{
public ScrollPanePaint() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(1000, 1000));
//I tried both true and false
panel.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(panel);
frame.add(scrollPane);
frame.setSize(200, 200);
frame.setVisible(true);
//To redraw the drawing constantly because that wat is happening in my code aswell because
//I am creating an animation by constantly move an image by a little
new Thread(new Runnable(){
public void run(){
Graphics g = panel.getGraphics();
g.setColor(Color.blue);
while(true){
g.fillRect(64, 64, 3 * 64, 3 * 64);
panel.repaint();
}
}
}).start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ScrollPanePaint();
}
});
}
}
我犯的错误很容易解决,但我不知道如何解决.
The mistake I make is probably very easy to fix, but I just can't figure out how.
推荐答案
如何在JPanel
上实现paintComponent()
?
覆盖getPreferredSize()
方法而不是使用setPreferredSize()
final JPanel panel = new JPanel(){
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// your custom painting code here
}
@Override
public Dimension getPreferredSize() {
return new Dimension(40, 40);
}
};
一些要点:
-
覆盖 JComponent#getPreferredSize()而不是使用
setPreferredSize()
了解更多信息我应该避免使用Swing中set(Preferred | Maximum | Minimum)Size方法的设置?
使用 Swing Timer 而不是 Java计时器适用于Swing应用程序.
Use Swing Timer instead of Java Timer that is more suitable for Swing application.
了解更多信息如何使用摇摆计时器
这篇关于在JScrollPane内的JPanel上绘画无法在正确的位置绘画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!