【发布时间】:2015-03-22 18:58:36
【问题描述】:
我是尝试创建 Java 接口的新手,我想创建一个作为大学项目的一部分。
目前我仍在处理打开界面,但似乎无法为我的框架设置背景图像。我已经观看了我能找到的所有 youtube 视频并浏览了所有论坛,但似乎仍然没有任何效果。
我看到的所有示例都没有按钮和文本框,所以我不确定这是否是问题,但在我的“尝试和捕捉”中,我只是不断地得到“图像不存在”,即使我已经放了具有正确文件名的图像。
就像我说的那样,我是使用接口的新手,所以据我所知,这可能非常简单,或者我并没有把它搞砸,但如果有人能帮忙,我会非常感激。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class CoopWelcome extends JFrame {
private ImageIcon image1;
private JButton b1;
private JTextField userName;
private static String password = "";
private JPanel backGround;
CoopWelcome() {
setLayout(new FlowLayout());
//creating username textbox
userName = new JTextField("");
userName.setText("Username");
userName.setForeground(Color.GRAY);
userName.setColumns(10);
getContentPane().add(userName);
//creating password textbox
JPasswordField passWord = new JPasswordField(10);
passWord.setEchoChar('*');
passWord.addActionListener(new AL());
getContentPane().add(passWord);
//adding the button and the label to the panel
b1 = new JButton("something");
getContentPane().add(b1);
//getting the image and displaying to the label
}
public static void main(String[] Args) {
//Creating the interface
CoopWelcome gui = new CoopWelcome();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("The Co-operative");
try {
gui.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("img.jpg")))));
} catch (IOException e) {
System.out.println("image doesn't exist");
}
}
static class AL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password)) {
JOptionPane.showMessageDialog(null, "Correct");
} else {
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
}
【问题讨论】:
-
这一定是我在 2 周内在这里的代码中看到的最糟糕的代码格式。但严重的是,您的文件路径不正确。您想使用相对于用户目录的路径,可以通过创建文件对象然后打印其路径或通过以下行找到该路径:
System.out.println(System.getProperty("user.dir"));。此外,您可能不希望将图像作为文件而是作为资源来获取。有一个谷歌关于我的意思的例子。 -
有关检索资源的更多信息,请参阅:StackOverflow: Jar get image as resource 和 Tutorial: Retrieving Resources。
-
"..college 项目 .. 设置背景图像.." 对于这个项目,直接在设计和文档方面投入额外的精力,而不是浮华。
标签: java swing interface jframe imageicon