2011-05-11 75 views
0

因此,我在AP計算機科學課上,我們的最終項目是製作一個程序,顯示我們學到的一堆不同概念。其中兩個正在顯示圖像,並添加按鈕。將圖像添加到JFrame中現有的JPanel中

我決定只做一個俗氣的基於決策的RPG,顯示if-else分支。我想出瞭如何獲得一個菜單,其中包含啓動按鈕,並打開一個輸入對話框。但我無法弄清楚如何將圖像添加到該按鈕所在的同一個JFrame中。您知道它是在按鈕上方或下方顯示圖像。我學會了如何顯示圖像,但這些例子都是隻顯示圖像的擴展類。我無法弄清楚如何在現有的代碼中調用某種繪圖或bufferedimage方法,或者在何處放置它。也許我可以打電話給另一個有圖像代碼的課程?這是我到目前爲止。

public class Smashing extends JPanel 
{ 

    public static void main(String[] args) 
    { 

    JFrame frame = new JFrame("Input Dialog Box Frame"); 
    JButton button = new JButton("Start Nigel's Adventure");  
    button.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent ae) 
     { 
     String str = JOptionPane.showInputDialog("What should Nigel do? : Enter a cardinal direction ex. n"); 
     if (str.equals("n")) 
     { 
      JOptionPane.showMessageDialog(null, "Nigel comes upon a tree "); 
      String str2 = JOptionPane.showInputDialog("What should Nigel do? :"); 
      if (str2.equals("climb")) 
      JOptionPane.showMessageDialog(null, "Nigel climbs up the tree "); 
      if (str2.equals("s")) 
      JOptionPane.showMessageDialog(null, "Nigel returns to the strating position "); 
     } 

     if (str.equals("s")) 
     { 
      JOptionPane.showMessageDialog(null, "Nigel comes upon boulder "); 
      String str3 = JOptionPane.showInputDialog("What should Nigel do? :"); 
     } 



     } 

    }); 
    JPanel panel = new JPanel(); 
    panel.add(button); 
    frame.add(panel); 
    frame.setSize(400, 400); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    } 
} 

我進口了一堆包了,我只是沒有包括在代碼中,哦,這也是一個普通的應用程序類,不是一個小程序。任何幫助是極大的讚賞。

回答

0

您可以使用一個JLabel來存儲您的圖片從文件或從一個緩衝區讀取:

ImageIcon image = new ImageIcon("path_to_image"); 
//or 
ImageIcon image = new ImageIcon (data) //where data is byte[] data 

然後創建您的JLabel:

JLabel label = new JLabel(image) 

要決定如何定位你的圖像添加的JLabel到所需佈局管理器的JPanel。

+0

完美,JLabel實際上工作。我將它添加到我的JPanel中,現在只有一件事是它使整個面板成爲一個按鈕!將解決它,謝謝。 – Cal 2011-05-13 13:00:15