1

我又带着另一个非常愚蠢的问题回来了。我已经阅读了其他一些 stackoverflow 帖子,并尝试遵循建议,但无济于事。我无法将 JPanel 背景更改为图像!我尝试将图像移动到我的 c:\,所以不是这样。

请提前帮助和感谢!

登录代码:

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

1 回答 1

4

转义路径中的反斜杠。

反斜杠是字符串中的特殊转义字符。 \b是一个特殊字符,而不是反斜杠和 b。要获得反斜杠,您需要其中两个\\

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

我建议File.separatorChar改用平台独立性,但C:几乎不独立于平台。

于 2012-07-06T18:14:45.953 回答