我有一个菜单按钮,一旦您单击它,它应该会转换为游戏状态,但是它将无法正常工作。这是我的MouseInput类。忽略除MousePressed方法之外的所有方法。
package com.game.src.main;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput implements MouseListener
{
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e)
{
int mx = e.getX();
int my = e.getY();
/**
public Rectangle playButton = new Rectangle(Game.WIDTH/2 + 120, 150, 100, 50);
public Rectangle helpButton = new Rectangle(Game.WIDTH/2 + 120, 250, 100, 50);
public Rectangle quitButton = new Rectangle(Game.WIDTH/2 + 120, 350, 100, 50);
*/
if (mx >= Game.WIDTH/2 + 120 && mx <= Game.WIDTH/2 + 220)
{
if (my >= 150 && mx <= 200)
Game.State = Game.STATE.GAME;
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
这是init方法,它是Game类的一部分。我将代码行加粗并斜体显示应该使用addMouseListener方法启用鼠标功能(但显然不起作用)。
public static enum STATE
{
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init()
{
requestFocus();
BufferedImageLoader loader = new BufferedImageLoader();
try
{
spriteSheet = loader.loadImage("/spritesheettemplate.png");
background = loader.loadImage("/bkg.png");
}
catch(IOException e)
{
e.printStackTrace();
}
addKeyListener(new KeyInput(this));
***addMouseListener(new MouseInput());***
tex = new Textures(this);
p = new Player(WIDTH/2*SCALE - 16, HEIGHT/2*SCALE - 16, tex);
c = new Controller(this, tex);
menu = new Menu();
eA = c.getEntityA();
eB = c.getEntityB();
c.addEnemy(enemyCount);
}
任何帮助将不胜感激。这是我游戏的最后一步。我正在关注有关YouTube的系列教程,但上传者从未回答任何问题,所以你们是我唯一的希望(我想我有点戏剧性)。如果您需要我发布更多代码部分,则可以这样做。
最佳答案
只需将ActionListener添加到该菜单按钮即可,而无需处理MouseListener。
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Game.State = Game.STATE.GAME;
}
});