最近自己在写俄罗斯方块,想练练巩固下所学的知识,添加图片遇到困难了,我在顶层窗口中添加了两个Panel,一个用来记录分数、画出下次出现的形状等信息,另一个是游戏界面,不会添加图片,用g.drawImage(Image ima, int x, int y, ImageObserver observer)这个方法添加图片到游戏界面后两个Panel都显示不出来了。
问下ImageObserver observer这个参数是不是设定要绘制的容器?
还有这个方法对不?若是不对该怎样添加?
若不用paint方法则背景颜色显示正常,就算只是写一个空的paint方法还是不能显示背景颜色。
源代码如下:
import java.awt.*;
import javax.swing.*;
public class Tetris extends JFrame { //游戏屏幕宽和高
private final int ScreenWidth = 450;
private final int ScreenHeight = 600;

Square square = new Square();
public static void main(String[] args) {
new Tetris().luanchFrame();
}

public void luanchFrame() {
JPanel ScorePanel = new JPanel();
JPanel GamePanel = new JPanel();
ScorePanel.setBackground(Color.BLACK);
GamePanel.setBackground(Color.RED);
ScorePanel.setSize(150, 600);
GamePanel.setSize(300, 600);
add(ScorePanel);
add(GamePanel);
//不改变窗口大小
this.setResizable(false); 
setTitle("俄罗斯方块");
setBounds(400, 100, ScreenWidth, ScreenHeight);
//关闭窗口
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ScorePanel.setVisible(true);
GamePanel.setVisible(true);
setVisible(true);
}

public void paint(Graphics g) {
square.drawSquare(g);
}
}import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.*;public class Square {
    //A:田字,B:长条,C:正Z,D:反Z,E:正7,F:反7.
enum Shape{A, B, C, D, E, F};
Shape s = Shape.A;

private Image image;

public void drawSquare(Graphics g) {
Color c = g.getColor();

switch(s) {
case A :
try {
image = ImageIO.read(new File("D:/JavaProject/Tetris0.2/picture/1.png"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(image, 200, 150, null);
break;
case B :
break;
case C :
break;
case D :
break;
case E :
break;
case F :
break;
}
}
}