1个回答
展开全部
图片放在包里面和类在同一个目录下,就是和*.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);
}
}
}
如果想要将图片放到其他目录,使用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);
}
}
}
追问
应经用JFrame组件做好窗口了 这个怎么加进去?? 水平有限。。。
追答
你把JPanel 当成 JFrame就行了啊,在显示的时候构造一个JFrame 加入JPanel 就OK了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询