【发布时间】:2019-01-04 16:45:59
【问题描述】:
我目前正在制作一款带有主菜单和您实际玩的世界的游戏。
我有一个名为Game 的类,它继承自JPanel 并实现了Runnable、MouseListener、KeyListener 和ActionListener 接口
(仅包括重要部分)
我还有两个课程 InWorldHandler 和 OutWorldHandler 分别用于处理世界内外的机制。
Game 类:
public class Game extends JPanel implements Runnable, KeyListener, MouseListener, ActionListener
{
protected JFrame frame;
private Timer timer = new Timer(25, this);
private World world;
private Player player = new Player();
private boolean draw;
Game(World world)
{
frame = new JFrame("Minecraft 2D");
this.world = world;
player.enterWorld(world, this);
}
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
if(draw)
{
g2d.setColor(new Color(255, 255, 255));
g2d.fillRect(0, 0, frame.getWidth(), frame.getHeight());
draw = false;
//Here, the in-game mechanics should be handled
if(player.inWorld())
{
Chunk chunk = player.getLoadedChunk();
for(int x = 0; x < 16; x++)
{
for(int y = 0; y < 16; y++)
{
Block block = chunk.getBlockAt(x, y);
BufferedImage texture = block.getTexture();
g2d.drawImage(block.getTexture(), x*32, y*32, texture.getWidth()*2, texture.getHeight()*2, null);
}
}
}
//Here, the out-game mechanics should be handled
else
{
}
}
}
@Override
public void actionPerformed(ActionEvent e)
{
this.repaint();
draw = true;
}
@Override
public void run()
{
draw = true;
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this);
frame.setMinimumSize(new Dimension(518, 540));
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.addKeyListener(this);
frame.addMouseListener(this);
frame.setFocusable(true);
frame.setVisible(true);
frame.pack();
timer.start();
}
}
其他两个类目前都有空体。我只是不知道该怎么做。
我希望当玩家在游戏中时InWorldHandler 类在面板上绘制,当玩家在主菜单中时OutWorldHandler 类在Game 类中调用。我该怎么做?
【问题讨论】:
-
一步一步来。首先获取
JFrame以正确显示JPanel,例如游戏面板。发布的代码没有。然后让它显示 anotherJPanel说菜单面板。在两个面板之间切换学习如何使用CardLayout
标签: java swing user-interface jpanel custom-painting