我遇到了一個奇怪的問題,我無法解決。我有兩班JFrame類:JFrame沒有從獨立的類更新圖形
public class TowerDefenceFrame extends JFrame {
public TowerDefenceFrame() {
super("Tower Defence");
setSize(1023, 708);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setResizable(false);
}
public static void main(String[] args) {
TowerDefenceFrame tdf = new TowerDefenceFrame();
tdf.setVisible(true);
Map.main(args);
}
}
和圖形類:
public class Board extends JPanel implements ActionListener {
BufferedImage road;
BufferedImage grass;
Timer time;
public Board() {
setFocusable(true);
time = new Timer(5, this);
time.start();
try {
road = ImageIO.read(new File("../road.png"));
grass = ImageIO.read(new File("../grass.png"));
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i <= Map.mapWidth - 1; i++) {
for (int l = 0; l <= Map.mapHeight - 1; l++) {
if (Map.mapArray[l][i] == 1) {
g.drawImage(road, (Map.blockSize * i), (Map.blockSize * l), this);
} else if (Map.mapArray[l][i] == 0) {
g.drawImage(grass,(Map.blockSize * i), (Map.blockSize * l), this);
}
}
}
repaint();
}
}
當我運行JFrame中出現的應用程序,但是從局級顯卡沒有。我正在尋找這個問題的答案,並找不到一個。我注意到,當我調整JFrame的大小時,板面上的圖像出現了。這讓我相信我不得不更新板類來獲取圖形。我試着在我的JFrame類中添加一個計時器循環來每隔1/2秒添加Board類。它沒有工作。我一直難住這個問題一段時間,我想知道你是否有任何可以幫助,
謝謝。
重寫的方法是paintComponent(Graphics)。所有的擺動組件只能從事件派發線程使用,而不能從主線程使用。 – 2013-03-24 14:17:47