gpt4 book ai didi

java - 设置 JPanel/JFrame 背景图片,我的第一次

转载 作者:行者123 更新时间:2023-11-29 03:45:04 25 4
gpt4 key购买 nike

我带着另一个非常愚蠢的问题回来了。我已经阅读了其他一些 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)

最佳答案

转义路径中的反斜杠。

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

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

我建议使用 File.separatorChar 来代替平台独立性,但是 C: 几乎不独立于平台。

关于java - 设置 JPanel/JFrame 背景图片,我的第一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com