简体   繁体   English

当JPanel位于JScrollPane中时,绘图如何工作?

[英]How does drawing work when a JPanel is inside a JScrollPane?

So I have a JPanel inside a JScrollPane (let's call them panel and pane for reference) So I added created the pane as so : 所以我在JScrollPane有一个JPanel (我们称它们为面板和窗格以供参考),所以我添加了创建窗格,如下所示:

JScrollPane pane = new JScrollPane(panel);

Then I added my pane to the frame. 然后,我将窗格添加到框架中。 So now I want to draw in my panel. 所以现在我想在面板上画画。 I first tried doing this by overriding the paintComponent method in my panel class. 我首先尝试通过覆盖面板类中的paintComponent方法来做到这一点。 I thought that my whole panel would be drawn and then I would be able to scroll through it because I added the panel to the pane. 我认为可以绘制整个面板,然后可以滚动浏览它,因为我将面板添加到了窗格中。 But every time I move the bar, it keeps trying to redraw. 但是每次我移动钢筋时,它都会不断尝试重绘。 Is my logic not right? 我的逻辑不对吗? Should I be drawing in another manner? 我应该以其他方式绘画吗?

I thought that my whole panel would be drawn and then I would be able to scroll through it because I added the panel to the pane. 我认为可以绘制整个面板,然后可以滚动浏览它,因为我将面板添加到了窗格中。 But every time I move the bar, it keeps trying to redraw. 但是每次我移动钢筋时,它都会不断尝试重绘。

This is just how JScrollPane s work, see the documentation for JViewport for a description of the algorithm. 这就是JScrollPane的工作方式,请参阅JViewport文档以获取算法说明。

If your drawing algorithm involves heavy processing, or you otherwise want to avoid having to redraw the panel so frequently, you can draw to an BufferedImage instead, and then use drawImage() from Graphics2d to draw the panel more efficiently on scroll updates. 如果绘制算法涉及繁重的处理,或者您希望避免不得不如此频繁地重新绘制面板,则可以绘制到BufferedImage ,然后使用Graphics2d中的drawImage()在滚动更新时更有效地绘制面板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM