2011-11-26 62 views
0

我正在創建一個應用程序,並在其中繪製圖像,並且它工作得很好。但出於某種原因,圖像已停止加載。該圖像位於我的項目目錄的根文件夾中。這裏是我的代碼:圖像只會有時加載

的JFrame:

package com.cgp.tetris; 

import java.awt.Dimension; 
import java.awt.Toolkit; 

import javax.swing.JFrame; 

public class TetrisFrame extends JFrame { 
     private static final long serialVersionUID = 1L; 

     public static void main(String[] args) { 
       new TetrisFrame(); 
     } 

     public TetrisFrame() { 
       add(new TetrisMenu()); 
       setTitle("Tetris"); 
       setSize(new Dimension(640, 576)); 
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       setVisible(true); 
       setResizable(false); 
       Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); 
       setLocation((d.width/2) - 320, (d.height/2) - 288); 
     } 
    } 

的JPanel:提前

package com.cgp.tetris; 

import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.swing.JPanel; 

public class TetrisMenu extends JPanel implements Runnable { 
    private static final long serialVersionUID = 1L; 
    private Thread thread; 
    private BufferedImage titletop, titlebottom; 

    public TetrisMenu() { 
     super(); 
    } 

    public void run() { 
     loadImages(); 
    } 

    private void loadImages() { 
     try { 
      titletop = ImageIO.read(new File("tetrispic.png")); 
      titlebottom = ImageIO.read(new File("titlebottom.png")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void addNotify() { 
     super.addNotify(); 
     thread = new Thread(this); 
     thread.start(); 
    } 

    public void paint(Graphics g) { 
     super.paint(g); 

     g.drawImage(titletop, 0, 0, 640, 440, null); 
     g.drawImage(titlebottom, 0, 440, null); 
    } 
} 

謝謝!

+0

請在此處發佈您的代碼,而不是脫機。 –

+0

好吧,我會這樣做的。 – Cg2916

回答

1

你的圖片加載不一致的原因是因爲加載是在一個線程中完成的,它具有不可預知的行爲,甚至更糟的是,該線程的啓動取決於何時調用addNotify(我猜測的是也是不可預知的)。你可以通過在構造函數中放入loadImages();然後repaint();來解決這個問題。擺脫addNotify覆蓋,run方法和Runnable修改器。這只是一個臨時解決方案(可能適合您的需求),因爲它不建議在EDT(Event-dispatch線程)上執行大量工作(加載許多映像),因爲它可能導致GUI無響應。圖像加載應該在SwingWorker的實例中完成,或者在構建GUI之前完成。

class TetrisMenu extends JPanel { 

    private static final long serialVersionUID = 1L; 
    private Thread    thread; 
    private BufferedImage  titletop, titlebottom; 

    public TetrisMenu() { 
     super(); 
     loadImages(); 
     repaint(); 
    } 

    private void loadImages() { 
     try { 
      titletop = ImageIO.read(new File("tetrispic.png")); 
      titlebottom = ImageIO.read(new File("titlebottom.png")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void paint(Graphics g) { 
     super.paint(g); 
     if (titletop != null) 
      g.drawImage(titletop, 0, 0, 640, 440, null); 
     if (titlebottom != null) 
      g.drawImage(titlebottom, 0, 440, null); 
    } 
} 
相關問題