【发布时间】:2019-08-30 04:59:31
【问题描述】:
我有一个游戏类,其中大部分渲染和框架都已完成。我有一个鼠标监听器类。我还有一个名为 Menu 的类,它在画布上绘制菜单。我希望它在我点击“开始”按钮时真正开始游戏,但似乎 MouseListener 没有收到鼠标点击。
我尝试在整个 Game 课程的许多地方添加 addMouseListener(new MouseInput()) 行,但它不起作用。
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput implements MouseListener
{
public void mousePressed(MouseEvent e)
{
int mx = e.getX();
int my = e.getY();
if(Game.STATE == 0)
{
if(mx >= 415 && mx <= 615)
{
if(my >= 350 && my <= 425)
{
Game.STATE = Game.STATE + 1;
}
}
if(mx >= 415 && mx <=615)
{
if(my >= 500 && my <= 575)
{
System.exit(1);
}
}
}
}
}
//游戏类
public class Game extends JFrame implements Runnable
{
private Canvas c = new Canvas();
public static int STATE = 0;
public static final int WIDTH = 1000;
public static final int HEIGHT = 800;
private Menu menu;
private FightState fight;
public Game()
{
//Forces program to close when panel is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//sets position and size of Frame
setBounds(0, 0, WIDTH, HEIGHT);
//puts Frame in center of the screen
setLocationRelativeTo(null);
//adds canvas to game
add(c);
//Makes frame visible
setVisible(true);
//creates our object for buffer strategy
c.createBufferStrategy(2);
// adds the mouse listner;
addMouseListener(new MouseInput());
}
public void update()
{
}
//renders the graphics onto the screen
public void render()
{
BufferStrategy bufferStrategy = c.getBufferStrategy();
Graphics g = bufferStrategy.getDrawGraphics();
super.paint(g);
//instantiates the menu object
menu = new Menu();
//instantiates the FightState object
fight = new FightState();
//renders the menu
if(STATE == 0)
{
menu.render(g);
}
//renders the fight stage
if(STATE == 1)
{
fight.render(g);
}
g.setFont(new Font("Monospaced", Font.PLAIN, 35));
g.drawString("STATE: " + STATE, 10, 400);
repaint();
//checks if mouseListener is working
System.out.print(STATE);
g.dispose();
bufferStrategy.show();
}
//game loop
public void run()
{
BufferStrategy bufferStrategy = c.getBufferStrategy();
long lastTime = System.nanoTime(); //long is an int that stores more space
double nanoSecondConvert = 1000000000.0 / 60; //frames/sec
double deltaSeconds = 0;
while(true)
{
long now = System.nanoTime();
deltaSeconds += (now-lastTime)/nanoSecondConvert;
while(deltaSeconds >=1)
{
update();
deltaSeconds = 0;
}
render();
lastTime = now;
System.out.println("STATE: " + STATE);
}
}
//main method
public static void main(String[] args)
{
Game game = new Game();
Thread gameThread = new Thread(game);
gameThread.start();
}
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 请对代码和代码 sn-ps、HTML/XML 等结构化文档或输入/输出使用代码格式。为此,请选择文本并单击消息发布/编辑表单顶部的
{}按钮。 3) 源代码中的一个空白行是永远需要的。{之后或}之前的空行通常也是多余的。
标签: java swing awt mouselistener