我的代码有问题,你能告诉它有什么问题吗?
这是代码:
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public static final int WIDTH = 600;
public static final int HEIGHT = 500;
public static void main(String avg[]) throws IOException {
Game abc = new Game();
}
public Game() {
try {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
image = ImageIO.read(new File(
"C:\\Users\\дНМ\\workspace\\Game\\image\\heroG.png"));
} catch (IOException ex) {
// handle exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
我得到一个窗口,但图片没有显示。如果你写出了问题所在,那就太好了!如果你仍然修复了 - 补充了代码,那就太棒了!
感谢您的关注。
UPD
谢谢你们。像这样更新代码,图像带出来了,但是背景不再是黑色了!
public Game() {
try {
image = ImageIO.read(new File(
"C:\\Users\\дНМ\\workspace\\Game\\image\\heroG.png"));
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
} catch (IOException ex) {
ex.printStackTrace();
}
}
如何给我返回黑色背景?)
UPD2
这是一个适合我的代码,谢谢大家。
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public static final int WIDTH = 600;
public static final int HEIGHT = 500;
public static void main(String avg[]) throws IOException {
Game abc = new Game();
}
public Game() {
try {
JFrame frame = new JFrame();
image = ImageIO.read(new File(
"C:\\Users\\дНМ\\workspace\\Game\\image\\heroG.png"));
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.getContentPane().add(this);
this.setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the
// parameters
}
}