我想添加一个功能,以便当鼠标移过按钮时,它会添加一个投影。目前我只是想让机制起作用。我的游戏循环调用了一种我知道有效的更新方法,但无论如何它都是
public void updateManager(double delta){
mhandler.updateCoordinates();
if(mhandler.getX() >= 144 && mhandler.getX() <= 444 && mhandler.getY() >= 784 && mhandler.getY() <= 980){
oversp = true;
}else{
oversp = false;
}
}
mhandler是我命名为MouseHandler类的东西。 然后我有我的渲染方法
public void render(){
repaint();
}
然后是我的绘画方法
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if(oversp){
System.out.println("Is over button");
g2d.setColor(Color.RED);
g2d.fillRect(144, 784, 300, 169);
}else{
System.out.println("Not over button");
g2d.setColor(Color.BLACK);
g2d.fillRect(144, 784, 300, 169);
}
}
当我运行该程序时,即使我在游戏循环中不断调用render(),它也只打印出不超过按钮两次。我真的不知道为什么不重新粉刷。任何帮助都非常有用!
这是我检测鼠标坐标
的方法 private int x,y;
public MouseHandler(){
x = 0;
y = 0;
}
public void updateCoordinates(){
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
x = (int) b.getX();
y = (int) b.getY();
}
public int getX(){
return x;
}
public int getY(){
return y;
}
游戏循环代码
public static void MenuLoop() {
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long lastFpsTime = 0;
int fps = 0;
while (isrunning) {
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double) OPTIMAL_TIME);
lastFpsTime += updateLength;
fps++;
if (lastFpsTime >= 1000000000) {
System.out.println("(FPS: " + fps + ")");
lastFpsTime = 0;
fps = 0;
}
menu.render();
menu.updateManager(delta);
try {
Thread.sleep((lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000);
} catch (Exception e) {
}
}
}public static void MenuLoop() {
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long lastFpsTime = 0;
int fps = 0;
while (isrunning) {
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double) OPTIMAL_TIME);
lastFpsTime += updateLength;
fps++;
if (lastFpsTime >= 1000000000) {
System.out.println("(FPS: " + fps + ")");
lastFpsTime = 0;
fps = 0;
}
menu.render();
menu.updateManager(delta);
try {
Thread.sleep((lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000);
} catch (Exception e) {
}
}
}
答案 0 :(得分:2)
Event Dispatch Thread包含添加了所有AWT事件的队列。每当你调用repaint
时,一个paint事件将在Event Dispatch Thread上排队。
因此,如果您在事件调度线程中处于无限循环中,那些绘制事件将永远排在队列中,等待无限循环结束。这就是永远不会调用paintComponent
的原因。
解决方案是用Swing timer替换无限循环。
Timer timer = new Timer(1000 / TARGET_FPS, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//...
}
});
timer.start();