2015-08-08 67 views
0

我正在使用Java開發這個項目,需要一個圖像來顯示,還有一個生物,以及播放歌曲/聲音的按鈕。我完成了按鈕和生物,但我可以弄清楚如何在佈局的北部顯示圖像以及中間部分的按鈕,任何幫助都會很棒。爲什麼我的圖像不能顯示在我的佈局中?

這是我的錯誤:在式容器的製造方法的附加(字符串,成分)是不適用的參數(圖像,字符串)

public void init() { 
    // image 
    myPicture = getImage(getCodeBase(), "sample.jpg"); 
    // THIS IS WHERE MY PROBLEM IS vvvvvvv  
    add(myPicture, BorderLayout.NORTH); 

    add(bio); 

    paneSouth.add(play); 
    getContentPane().add(paneSouth, BorderLayout.SOUTH); 
    mySound = getAudioClip(getDocumentBase(), "sample.wav"); 
    play.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      mySound.play(); 
     }});  
} 

public void paint(Graphics g){ 
    g.drawImage(myPicture, 10, 10, this); 
} 

private JPanel paneSouth = new JPanel(); 
private TextArea bio = new TextArea("bio thing"); 
private JButton play = new JButton("Play"); 
private AudioClip mySound; 
private Image myPicture; 

}

編輯:

public void init() { 
    // image 
    ImageIcon icon = new ImageIcon(myPicture); 
    JLabel myLabelImage = new Image(icon); 
    add(myLabelImage, BorderLayout.NORTH); 

    // bio 
    add(bio); 
    add(bio, BorderLayout.CENTER); 

    // sound 
    paneSouth.add(play); 
    getContentPane().add(paneSouth, BorderLayout.SOUTH); 
    mySound = getAudioClip(getDocumentBase(), "sample.wav"); 
    play.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      mySound.play(); 
     }});  
} 

private JPanel paneSouth = new JPanel(); 
private TextArea bio = new TextArea("bio."); 
private JButton play = new JButton("Play"); 
private AudioClip mySound; 
private Image myPicture; 
} 

回答

3

我想你正在使用JApplet,因爲你正在使用Swing組件。嘗試是這樣的:

public class ImageApplet extends JApplet { 

    private JPanel paneSouth = new JPanel(); 
    private JTextArea bio = new JTextArea("bio thing"); 
    private JButton play = new JButton("Play"); 
    private Image myPicture; 
    private ImageIcon icon; 
    private JLabel label; 

    public void init() { 
     try { 
      URL pic = new URL(getDocumentBase(), "sample.jpg"); 
      myPicture = ImageIO.read(pic); 
      icon = new ImageIcon(myPicture); 
      label = new JLabel(icon); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     // add image 
     add(label, BorderLayout.NORTH); 
     // bio 
     add(bio, BorderLayout.CENTER); 
     // sound 
     paneSouth.add(play); 
     add(paneSouth, BorderLayout.SOUTH); 

     // here add your sound declaration and button event... 
    } 

    @Override 
    public void paint(Graphics g) { 
     super.paint(g); 
    } 
} 

並嘗試改變你TextAreaJTextArea,因爲你只使用Swing組件。

+0

嘿,謝謝你的回覆我只是有一個簡單的問題,當我試圖將它添加到這部分... add(myPicture,BorderLayout.NORTH); ...我得到這個...類型Container中的方法add(String,Component)不適用於參數(Image,String)....你知道我該如何解決這個問題嗎? – Joe

+0

對不起,我添加了一些註釋,你需要使用一個組件,就像一個'JLabel',它將包含你的圖像。 –

+0

嘿,再次感謝我以爲你不能從圖像轉換爲JLabel? – Joe

相關問題