To draw a map on the canvas and insert the map matrix from the Map class into the MyFrame class, you can do the following:
- Create a method in the MyCanvas class to draw the map using Graphics.
- Pass the map matrix from the GameMapSet object to MyCanvas through its constructor.
- Call the drawMap method in MyCanvas from within the actionPerformed method of button1 ActionListener.
Here’s an example code snippet for drawing a simple grid-based map with different colors for different types of tiles:
import java.awt.*;
public class MyCanvas extends Canvas {
private static final int TILE_SIZE = 40; // size of each tile in pixels
private GameMapSet map;
public MyCanvas(GameMapSet map) {
this.map = map;
}
public void drawMap(Graphics g) {
for (int row = 0; row < map.getHeight(); row++) {
for (int col = 0; col < map.getWidth(); col++) {
int x = col * TILE_SIZE;
int y = row * TILE_SIZE;
switch(map.getTile(row, col)) {
case WALL:
g.setColor(Color.GRAY);
break;
case BOX:
g.setColor(Color.ORANGE);
break;
case GOAL:
g.setColor(Color.YELLOW);
break;
default: // EMPTY
g.setColor(Color.WHITE);
break;
}
g.fillRect(x, y, TILE_SIZE, TILE_SIZE);
}
}
}
}
And here’s how you can use it in your button1 ActionListener:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
JPanel panel2=new JPanel();
panel2.setBackground(new Color(255,217,229));
Canvas canvas=new MyCanvas(map);
canvas.setPreferredSize(new Dimension(map.getWidth() * TILE_SIZE, map.getHeight() * TILE_SIZE));
panel2.add(canvas);
frame.setContentPane(panel2);
JButton button8=new JButton("我还是喜欢灰姑娘,不救公主了(闯不过,退出关卡)");
button8.setBackground(Color.PINK);
button8.setBorder(BorderFactory.createRaisedBevelBorder());
panel2.add(button8,BorderLayout.SOUTH);
frame.revalidate();
frame.setVisible(true);
Graphics g = canvas.getGraphics();
((MyCanvas)canvas).drawMap(g);
}
});
Note that this is just a simple example and you may need to modify it according to your specific requirements. Also, make sure to handle the case where the map matrix is null or empty.




