2013-12-14 34 views
0
public FinalProject() throws IOException 
    { 
     String fontType = JOptionPane.showInputDialog("What kind of font would you like? "); 
     String backgroundColor = JOptionPane.showInputDialog("Would you like your background color to be blue, green or pink?"); 
     if(backgroundColor.equals("blue")) 
     { 
      setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad.png"))); 
     } 
     else if(backgroundColor.equals("pink")) 
     { 
      setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad2.png"))); 
     } 
     else if(backgroundColor.equals("green")) 
     { 
      setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad3.png"))); 
     } 
     else 
     { 
      JOptionPane.showMessageDialog(c, "Sorry color not recognized so color was set to the defalut (blue)"); 
      setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad.png"))); 
     } 
     Font font = new Font(fontType, Font.BOLD, 30); 
     txt = new JTextField(13); //create a text field 
     Color color = new Color(255,0,0); 
     txt.setForeground(color); 
     txt.setFont(font); 
     c = getContentPane(); 

     setLayout(new FlowLayout()); 
     c.add(txt); 

     buttons = new HashMap <String, JButton>(); 

     String[] names = {"1","2","3","4","5","6","7","8","9","0","+","-","x","/","sin","cos","tan","arcsin","arccos","arctan","log","abs","sqrt","exp","M","M Recall","C","="}; 
     for (String d: names) 
     { 
      BufferedImage pic1 = ImageIO.read(new File("button1.jpg")); 
      JButton i = new JButton(new ImageIcon(pic1)); 
      i.setPreferredSize(new Dimension(75,75)); 
      c.add(i); 
      i.addActionListener(this); 
      buttons.put(d, i); 
     } 

?ImageIO說它無法讀取文件,並且該文件已在文件夾 中。
setSize(400,650); setVisible(true); setResizable(false); txt.setEditable(false);ImageIO異常無法讀取我的輸入文件。對於讀取文件時的緩衝圖像

+0

1)請不要忘記加上「?」提問!有些人在頁面中搜索'?'如果'問題'中不存在,則直接進入下一個(實際)問題。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 3)請使用代碼格式設置代碼,輸入/輸出和結構化文檔,如HTML或XML。爲此,請選擇樣本並單擊郵件發佈/編輯表單上方的「{}」按鈕。 –

+0

'BufferedImage pic1 = ImageIO.read(new File(「button1.jpg」));'部署時,這些資源可能會變成[tag:embedded-resource]。在這種情況下,資源必須通過'URL'而不是'File'訪問。查看標籤的[info page](http://stackoverflow.com/tags/embedded-resource/info),以獲得一個「URL」。 –

回答

0

從評論我認爲你必須使用ImageIO.#read(URL)方法。另外你爲什麼在for循環中做同樣的事情?

URL url = this.getClass().getResource("/path/to/resource/button1.jpg"); 
BufferedImage pic1 = ImageIO.read(url); 
JButton i = new JButton(new ImageIcon(pic1)); 
i.setPreferredSize(new Dimension(75,75)); 
c.add(i); 
i.addActionListener(this); 

這應該外面做的for循環,並在for循環

String[] names = {"1","2","3","4","5","6","7","8","9","0","+","-","x","/","sin","cos","tan","arcsin","arccos","arctan","log","abs","sqrt","exp","M","M Recall","C","="}; 
for (String d : names) 
{ 
    buttons.put(d, i); 
}