我是尝试创建 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");
}
}
}
}