这是我的 View 类
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class View
{
JFrame frame;
JPanel background;
public View()
{
frame = new JFrame("Platformer");
background = new JPanel(new BorderLayout());
BuildMenu();
SetBackground();
BuildLowerPanel();
frame.getContentPane().add(background);
frame.setSize(800, 700);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private void BuildMenu()
{
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
frame.setJMenuBar(menuBar);
JMenuItem i = new JMenuItem("Resume");
i.setActionCommand("RESUME");
JMenuItem j = new JMenuItem("Pause");
j.setActionCommand("PAUSE");
menu.add(i);
menu.add(j);
}
public void paintComponent(Graphics g)
{
}
private void BuildLowerPanel()
{
}
}
这是我的模型类,它基本上只读取图像
package introGUI;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Model
{
private BufferedImage img;
public void ReadImage()
{
try
{
img = ImageIO.read(new File("C:\\Users\\p333kle\\Pictures\\lvl1.jpg"));
}
catch(IOException e)
{
System.err.println("Error: Couldn't load background image");
}
}
}
现在我想向我的 View 类添加一个 setBackground 方法,该方法将在初始化级别时由 Controller 调用,并将接收模型读取的图像。然而,我对如何执行此操作感到困惑,因为我确信我必须使用paintComponent,然后绘制我已读取的图像。但是我不确定如何继续编写 setBackground 方法。
最佳答案
如图here ,使用observer pattern当模型中启动级别更改时,让模型通知 View 。在平台游戏的特定情况下,模型可以管理关卡(可能由枚举值标识),而 View 可以选择匹配的背景(可能是从相关集合中选择的)。请参阅 example 中的 RCImage
引用。
关于java - 如何使用 MVC 和 PaintComponent 在我的平台游戏的 View 类中创建 setBackground 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862921/