2013-08-26 22 views
2

我有一個GUI創建JPanel和「開始」按鈕。我需要的只是當我點擊「開始」時,圖像將被加載並顯示在該JPanel上。 但我的問題是,當我點擊「開始」,什麼也沒有發生。 任何人都可以幫我解決這個問題嗎? 這是我的代碼:圖像不會出現在JPanel使用BufferedImage

private BufferedImage image; 
public class ImagePanel extends JPanel { 
    public ImagePanel() { 
     try { 
      image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg")); 
     } catch (IOException ex) { 
     // handle exception... 
     } 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawImage(image, 0, 0, null); 
    } 
} 

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {           
    stopBtn.setEnabled(true); 
    startBtn.setEnabled(false); 
    imageArea.add(new ImagePanel()); // imageArea is the JPanel in the GUI 
} 

當我通過如下創建一個新的JFrame,即JFrame的出現與我添加的圖像替換2行imageArea的。

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {           
    stopBtn.setEnabled(true); 
    startBtn.setEnabled(false); 
    JFrame test = new JFrame("Window"); 
    test.add(new ImagePanel()); 
    test.setSize(image.getWidth(), image.getHeight() + 30); 
    test.setVisible(true); 
} 

回答

5

當你將組件添加到一個可見的GUI的基本代碼是:

panel.add(...); 
panel.revalidate(); 
panel.repaint(); 

然而,這可能不會是因爲在默認情況下幫助一個JPanel使用FlowLayout中和的FlowLayout尊重的大小組件。由於您沒有覆蓋getPreferredSize()方法,因此ImagePanel的大小爲(0,0)。

沒有必要創建自定義面板來繪製圖像。只需使用JLabelIcon,然後讓標籤擔心尺寸。不要重新發明輪子。

我建議你閱讀Swing tutorial的基礎知識。也許How to Use Labels的部分將是一個很好的開始。本教程還將向您展示一個更好的方式來設計您遵循Swing指南的課程。

+0

對不起,創建新問題:( 我按照你的說法試了JLabel,但它仍然無法解決我的問題。圖像仍然沒有顯示在JPanel –

+0

@ user2716653說不起作用並不能提供任何信息,你需要發佈一個'SSCCE' 。 – camickr

+0

@ user2716653 :問題可能是找不到圖像,如果是這種情況,請嘗試在catch塊中寫入'ex.printStackTrace()',並查看可能提供更多詳細信息的堆棧跟蹤(如果有的話): - ) –

2

首先確定一點:

try { 
     image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg")); 
    } catch (IOException ex) { 
     ex.printStacktrace(); // see if there is an exception, like not finding or something 
    } 

比: 如果添加一個面板,比需要佈局刷新和GUI刷新:

imageArea.add(new ImagePanel()); 
imageArea.revalidate(); // refresh layout 
imageArea.repaint(); // shedule painting 
+0

奇怪,我試過了。沒有什麼東西出現在catch異常中,所以我認爲沒有任何異常。 ()和repaint(),但它仍然不起作用... :( –

+0

@ user2716653比你添加新的組件不可見死去佈局。設置一個新的BorderLayout()並將其添加到中心約束,也許你有一個NullLayout左右 – 2013-08-26 05:12:49