无法让我的鼠标侦听器为高中的口袋妖怪游戏工作



我有一个游戏类,其中大部分渲染和框架都已完成。我有一个鼠标侦听器类。我还有一个名为 Menu 的类,它在画布上绘制菜单。我希望它在我单击"开始"按钮时实际启动游戏,但似乎鼠标侦听器没有收到鼠标单击。

我尝试在整个游戏类的许多地方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();
}
}

如果您使用的是BufferStrategy,请不要在JFrame上调用super.paint(g);。 只需直接绘制到缓冲区即可。您还应该将MouseListener添加到Canvas,而不是框架中。

Canvas

布置在窗口的框架边界内,这意味着它将偏移并小于实际框架本身。

鼠标事件会自动转换为源坐标上下文,这意味着您当前正在尝试将来自帧坐标上下文的值与Canvas使用的值进行比较,这些值是不同的

一个问题:如果缓冲区没有"图形方法"(如fillRect()),我将如何直接绘制到缓冲区?

Graphics g = bufferStrategy.getDrawGraphics()为您提供Graphics上下文,然后直接对其进行绘制。

您不想直接调用paint(永远),因为它可以被系统调用,并且您可能会遇到竞争条件和其他问题

Swing使用不同的绘画算法,您已通过使用BufferStrategy选择退出,这意味着您不能再使用"正常"的 Swing 绘画过程,而是必须编写自己的

最新更新