我正在使用的項目是用於玩桌面遊戲的計算機間實用程序,其中的關鍵部分是交互式網格/地圖。那麼我已經建立了自定義地圖創建功能,並希望屏幕能夠顯示非常大的地圖,以及非常小的地圖。爲此,我創建了一系列可以顯示任意大小的網格的類。然而,我想要做的就是將JPanel與JScrollPane合併到一起,從而爲地圖創造無限空間。當我嘗試這樣做時,完全脫離JScrollPane的地圖完全不會繪製。我懷疑它與Graphics上下文有關,但迄今一直無法找到解決方案。在JScrollPane中重繪一個JPanel
在以下代碼中,重新標記滾動行並在初始化中切換grid.draw方法調用以查看我希望它的樣子。
完整的代碼如下:
package pac;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class MainScreen extends JFrame
{
int width, height, x, y;
Grid grid;
public static void main(String[] args)
{
MainScreen mainScreen = new MainScreen();
mainScreen.setVisible(true);
}
public MainScreen()
{
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
float factor = 1.25f;
width = (int)(dim.width/factor);
height = (int)(dim.height/factor);
x = (int)(dim.width/(factor * 8));
y = (int)(dim.height/(factor * 8));
setBounds(x,y,width,height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("DnD Main Screen");
setVisible(true);
grid = new Grid();
JScrollPane scrollPane = new JScrollPane(grid);
scrollPane.setBounds(212,0,650,500);
scrollPane.setViewportView(grid);
add(scrollPane);
this.setLayout(null);
Thread draw = new Thread()
{
public void run()
{
while(true)
{
Graphics g = getGraphics();
grid.repaint();
//grid.paintComponents(getGraphics());
g.setColor(Color.blue);
g.fillRect(0 + 8, 0 + 30, 212, 200);
g.fillRect(863 + 8, 0 + 30, 212, 200);
g.setColor(Color.red);
g.fillRect(0 + 8, 200 + 30, 212, 375);
g.fillRect(863 + 8, 200 + 30, 212, 375);
try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
Thread.yield();
}
}
};
draw.start();
}
public class Grid extends JPanel
{
Tile[][] tiles;
public int x, y, across, down;
public int topBar = 30;
public int skinnyBar = 8;
public Grid()
{
this.setPreferredSize(new Dimension(600,600));
x=212 + skinnyBar;
y=0+topBar;
across = 13;
down = 9;
tiles = new Tile[across][down];
for(int i = 0; i<across; i++)
for(int j = 0; j<down; j++)
{
tiles[i][j] = new Tile(x+(i*50),y+(j*50),50);
}
this.setVisible(true);
}
public void paintComponents(Graphics g)
{
//super.paintComponents(g);
draw(g);
}
public void draw(Graphics g)
{
for(int i = 0; i<across; i++)
for(int j = 0; j<down; j++)
{
g.setColor(Color.black);
for(int k =0; k< 5; k++)
g.drawRect(tiles[i][j].x+k, tiles[i][j].y+k, tiles[i][j].side-k*2, tiles[i][j].side-2*k);
}
}
private class Tile
{
int x, y, side;
public Tile(int inX, int inY, int inSide)
{
x=inX;
y=inY;
side=inSide;
}
}
}
}
我一直在這一段時間,一直沒能找到和問題相似,足以雷找到修復。有什麼建議?謝謝,麻煩您了。
搖擺的第1章,永遠,永遠,永遠不要畫什麼爲一個好地方做的'事件調度Thread'外的UI,永遠 – MadProgrammer 2012-08-08 05:58:33