java调用repaint无效,从Java中另一个类调用repaint?

开发者在测试Java游戏人物移动时遇到问题,无法在Person类中直接调用GamePanel的repaint方法。通过使用Swing Timer,解决了定时更新游戏面板的问题,涉及多线程管理和GUI操作同步。
摘要由CSDN通过智能技术生成

I'm probably doing this wrong, so please be nice.

I'm developing a Java game, and I'm at the stage of testing character movement / animation.

The "person" can move up down left and right on a grid.

The class the grid is drawn in is the gamePanel class.

The buttons are in the gameControlPanel class.

I have a button which spawns a person on the grid.

I then have a button to move the person up down left and right.

When the move up button is pressed, it calls the move up method from the person class.

(At the moment, I'm only testing one "person" at a time.)

In that method is the following code...

int move = 10;

while(move!=0)

{

setTopLeftPoint(new Point((int)getTopLeftPoint().getX(),

(int)getTopLeftPoint().getY() - 3));

try

{

Thread.sleep(300);

} catch (InterruptedException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

move-=1;

}

The problem is that I can't seem to call the repaint method for the gamePanel class from within the Person class.

To get around this, I created a timer in the gamePanel class which repaints every 20ms.

When I press the up button after the person is spawned, the button remains pressed down until the cycles of the while loop have been completed, and then the circle representation of the person is displayed in the grid square above.

I will try to answer any questions regarding this.

解决方案

If you want to repaint at a certain interval, javax.swing.Timer is probably the class for you. In the specific case of repaint you can call it from a non-EDT thread, but you may get yourself into difficulty as you are now dealing with multiple threads.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值