2012-07-06 48 views
1

我回來了又一個非常愚蠢的問題。我已經閱讀了一些其他的stackoverflow帖子,並試圖按照建議,但無濟於事。我無法讓JPanel背景更改爲圖像!我試圖將圖像移動到我的c:\,所以不是這樣。設置JPanel/JFrame背景圖像,我的第一次

請幫助和提前致謝!

登錄代碼:

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.swing.*; 


public class login implements ActionListener{ 


    JTextField gusername; 
    JTextField gpassword; 
    static String username; 
    static String password; 

    void logini() throws IOException { 

     JFrame window = new JFrame("Login"); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.setSize(300, 250); 
     window.setResizable(false); 
     window.setVisible(true); 

     JPanel mainp = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     window.add(mainp); 



     BufferedImage myPicture = ImageIO.read(new File("c:\bgd.png")); 
     JLabel picLabel = new JLabel(new ImageIcon(myPicture)); 
     mainp.add(picLabel); 




     c.gridx = 0; 
     c.gridy = 1; 
     gusername = new JTextField(); 
     gusername.setText("Username"); 
     mainp.add(gusername, c); 

     c.gridx = 0; 
     c.gridy = 2; 
     gpassword = new JTextField(); 
     gpassword.setText(" password "); 
     mainp.add(gpassword, c); 

     c.gridx = 0; 
     c.gridy = 3; 
     JButton login = new JButton("Login"); 
     mainp.add(login, c); 

     login.addActionListener(this); 
     login.setActionCommand("ok"); 
    } 


    public void actionPerformed(ActionEvent e) { 
     if (e.getActionCommand().equalsIgnoreCase("ok")){ 
      try { 
       this.username = (gusername.getText()); 
       this.password = (gpassword.getText()); 
       System.out.println("0"); 

      } 
      catch(NumberFormatException ex){ 
       System.out.println("ERROR: Could not preform function: 7424"); 

      } 
     } 
    } 


} 

錯誤:

Exception in thread "main" javax.imageio.IIOException: Can't read input file! 
    at javax.imageio.ImageIO.read(Unknown Source) 
    at login.logini(login.java:34) 
    at Main.main(Main.java:10) 

回答

4

逃避你的路徑反斜槓。

反斜槓是字符串中特殊的轉義字符。 \b是一個特殊字符,不是反斜槓和b。要得到一個反斜槓,你需要兩個\\

BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png")); 

我會建議使用File.separatorChar而不是爲平臺的獨立性,但C:幾乎與平臺無關。

+0

非常感謝的人! :) – 2012-07-06 18:16:43

+0

另一個建議是從您的應用程序中讀取字符串,並使用該字符串代替硬編碼您的位置。確保你將程序移動到哪裏,移動圖片的位置,否則它將無法工作。 – 2012-07-06 18:17:35

+0

@Erick Robertson現在圖像已經啓動,爲什麼我的其他組件不出現? – 2012-07-06 18:19:08