所以我在 JScrollPane 中有 JPanel。有没有可能的方法在 JPanel 上仅显示可见区域?现在我的代码如下所示:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < m_xTiles; i++)
{
for(int j = 0; j < m_yTiles; j++)
{
m_mapTiles.get(i).get(j).DrawImage(g);
}
}
}
这不是我想要的东西,因为它显示了所有内容,当我想制作一张非常大的 map 时,移动非常慢。我想在屏幕上获得可见的矩形 - 四个像素的位置,然后我将计算我自己的 x 和 y :)
最佳答案
通常,图形系统关心可见边界之外的裁剪操作,因此这些操作变为无操作并且并不昂贵。因此,在大多数情况下,您不需要处理这些信息,因为图形操作是绘画时昂贵的部分。
但是,有时您可能会遇到这样的情况:在调用 Graphics
对象之前执行的操作变得昂贵,即,如果您有一个非常大但只有部分可见组件(如您所描述的)。在这种情况下,访问剪切信息以执行手动跳过可能会很有用,特别是当您平铺区域时,因此计算要处理的项目相当容易:
public void paintComponent(Graphics g) {
super.paintComponent(g);
// I assert equal tiling of the actual size here, otherwise you may define
// the tile sizes as constants and calculate preferredSize as tileWidth*m_xTiles
// and tileHeight*m_yTiles, respectively
final int tileWidth=getWidth()/m_xTiles;
final int tileHeight=getHeight()/m_yTiles;
Rectangle clip = g.getClipBounds();
int firstX, lastX, firstY, lastY;
if(clip == null) {
firstX=0; lastX=m_xTiles-1;
firstY=0; lastY=m_yTiles-1;
}
else {
firstX=clip.x/tileWidth; lastX=(clip.x+clip.width)/tileWidth;
firstY=clip.y/tileHeight; lastY=(clip.y+clip.height)/tileHeight;
}
// note that the loop condition is <= now to handle partially visible tiles
for(int i = firstX; i <= lastX; i++)
{
for(int j = firstY; j <= lastY; j++)
{
m_mapTiles.get(i).get(j).DrawImage(g);
}
}
}
关于java 如何在 JPanel 中仅显示可见区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27926342/