图片放在包里面和类在同一个目录下,就是和*.class 同一个目录
如果想要将图片放到其他目录,使用Image img = ImageIO.read(new File(String filename));作相应修改吧
import java.awt.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GameMode extends JFrame {
Image img;
public GameMode() {
super("哈哈");
try {
img = ImageIO.read(getClass().getResource("login.jpg"));
} catch (IOException e1) {
e1.printStackTrace();
}
this.getContentPane().add(new MyPanel(img), BorderLayout.CENTER);
this.setSize(400, 300);
}
public static void main(String args[]) {
GameMode f = new GameMode();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private Image tmp;
public MyPanel(Image img) {
this.tmp = img;
}
public void paintComponent(Graphics g) {
if (tmp == null)
g.drawString("mg ==null", 10, 10);
g.drawImage(tmp, 0, 0, this.getWidth(), this.getHeight(), this);
g.setColor(Color.yellow);
g.drawString("图像测试", 10, 20);
for(String x:ImageIO.getReaderMIMETypes()){
System.out.println(x);
}
}
}