我又回到了另一个非常愚蠢的问题。我已经阅读了其他一些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)
答案 0 :(得分:4)
逃避路径中的反斜杠。
反斜杠是字符串中的特殊转义字符。 \b
是一个特殊字符,而不是反斜杠和b。要获得反斜杠,您需要其中两个\\
。
BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
我建议使用File.separatorChar
代替平台无关,但C:
几乎不依赖于平台。