如果你想在画布中插入另一个类的地图矩阵,可以使用该类的方法来获取地图信息,并在画布上绘制出来。具体步骤如下:
- 在需要绘制地图的位置创建一个新的类Map,其中包含一个二维数组map表示地图矩阵。
 - 在Map类中定义一个方法getMap(),用于返回地图矩阵。
 - 在MyFrame类中创建Map对象,并调用其getMap()方法获取地图矩阵。
 - 使用Graphics对象在画布上根据地图矩阵绘制出整个游戏界面。
 
示例代码如下:
public class Map {
    private int[][] map;
    public Map() {
        // 初始化地图
        map = new int[][]{
                {0, 0, 0, 0, 0},
                {0, 1, 1, 1, 0},
                {0, 2, 3, 4, 0},
                {0, 5, 6, 7, 0},
                {0, 0, 0, 0, 0}
        };
    }
    public int[][] getMap() {
        return map;
    }
}
public class MyCanvas extends Canvas {
    private Map map;
    public MyCanvas(Map map) {
        this.map = map;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        int[][] arr = map.getMap();
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] == 1) { // 绘制墙壁
                    g.setColor(Color.GRAY);
                    g.fillRect(j * 50, i * 50, 50, 50);
                } else if (arr[i][j] == 2) { // 绘制玩家
                    g.setColor(Color.RED);
                    g.fillOval(j * 50 + 10, i * 50 + 10, 30, 30);
                } else if (arr[i][j] >=3 && arr[i][j] <=7) { // 绘制箱子
                    g.setColor(Color.BLUE);
                    g.fillRect(j * 50 + 5, i * 50 +5 ,40,40);
                }
            }
        }
    }
}
public class MyFrame extends JFrame {
    public static void createAndShow() {
        // ...
        JButton button1 = new JButton("开始游戏");
        panel.add(button1);
        Map map = new Map();
        MyCanvas canvas = new MyCanvas(map);
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.getContentPane().removeAll();
                JPanel panel2=new JPanel();
                JPanel panel3=new JPanel();
                panel2.add(panel3);
                panel2.setLayout(new BorderLayout());
                frame.setContentPane(panel2);
                frame.revalidate();
                JButton button8=new JButton("我还是喜欢灰姑娘,不救公主了(闯不过,退出关卡)");
               // ...
                canvas.setPreferredSize(new Dimension(250,250));
                
                panel3.add(canvas);
               // ...
            }
        });
       // ...
    }
   // ...
}
                                    

        
        
        
        
        
        
        
        
        
        
                
                
                
                
                
                
                