【发布时间】:2021-06-24 05:14:38
【问题描述】:
我目前正在为学校使用 Java 开发 2D 游戏。我们必须使用抽象工厂设计模式。对于 2D 实现,我使用如下工厂:
public class Java2DFact extends AbstractFactory {
public Display display;
private Graphics g;
public Java2DFact() {
display = new Display(2000, 1200);
}
@Override
public PlayerShip getPlayership()
{
return new Java2DPlayership(display.panel);
}
在我的显示类中,我创建了一个 JFrame 和 Jpanel
public class Display {
public JFrame frame;
public JPanel panel;
public int width, height;
public Display(int width, int height) {
this.width = width;
this.height = height;
frame = new JFrame();
frame.setTitle("SpaceInvaders");
frame.setSize(1200,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
}
};
panel.setFocusable(true);
frame.add(panel);
}
}
现在,我从我的主游戏循环中调用 Java2DPLayership 类中的可视化方法来可视化我的 Playership
public class Java2DPlayership extends PlayerShip {
private JPanel panel;
private Graphics2D g2d;
private Image image;
private BufferStrategy bs;
public Java2DPlayership(JPanel panel) {
super();
this.panel = panel;
}
public void visualize() {
try {
image = ImageIO.read(new File("src/Bee.gif"));
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
//g.setColor(new Color(0, 0, 0));
//g.fillRect(10, 10, 12, 8);
g.drawImage(image, (int) super.getMovementComponent().x, (int) super.getMovementComponent().y, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
panel.repaint();
} catch(Exception e){
System.out.println(e.toString());
}
}
}
我的目标是将 JPanel 传递给每个实体,并让它在显示之前将其内容绘制到面板上。但是我似乎无法弄清楚如何做到这一点。当通过更改面板的图形来使用这种方法时,我得到了很多闪烁。
【问题讨论】:
-
您应该只从您在 JPanel 中覆盖的
paintComponent的上下文中绘制。无处。这意味着一旦在paintComponent中,您可以调用其他方法并将图形上下文作为参数传递。并在每次调用 repaint 时尽可能缩短绘制逻辑(在时间上)以避免阻塞事件调度线程。