我正在尝试制作汽车游戏。在创建Coin线程之前,我的keyListener在主线程上工作正常,但是当我启动Coin线程时,只有添加的按钮(Coin)有效,而keyListener无效。
我该如何运行两个线程而没有任何问题,请帮助?
///我的Java代码如下[Eclips]
class Coin implements Runnable
{
int coinX=120,coinY=0;
JFrame frame;
JLabel coin;
JButton btn;
Coin(JFrame frame)
{
this.frame=frame;
btn=new JButton("COIN");
//coin=new JLabel();
//coin.setIcon(new ImageIcon("coin_view.png"));
frame.add(btn);
}
public void run() {
try {
for (int i=0;i<300;i=i+5)
{
btn.setBounds(coinX,i,120,120);
Thread.sleep(200);
}
//System.out.println("coin over");
} catch (Exception e) {}
}
}
public class Main extends JFrame implements KeyListener{
JLabel enemy,player;
JPanel panel;
int playerXLoc=90,playerYLoc=470,playerWidth=120,playerHeight=120;
int enemyXLoc=120;
Main()
{
setLayout(null);
player=new JLabel();
player.setIcon(new ImageIcon("player_car.png"));
setTitle("Score : 100 , Lifes : 3");
player.setBounds(playerXLoc, playerYLoc, playerWidth, playerHeight);
JLabel background = new JLabel(new ImageIcon("road.png"));
Coin coinObj=new Coin(this);
Thread startTherad=new Thread(coinObj);
startTherad.start();
addKeyListener(this);
add(player);
this.setSize(400,650);
setVisible(true);
}
public static void main(String[] args)
{
Main start=new Main();
}
@Override
public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
if(playerXLoc>90)
{
playerXLoc -=80;
player.setBounds(playerXLoc, playerYLoc, playerWidth, playerHeight);
}
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
if(playerXLoc<250)
{
playerXLoc+=80;
player.setBounds(playerXLoc, playerYLoc, playerWidth, playerHeight);
}
}
System.out.println("new x: "+playerXLoc);
}
public void keyReleased(KeyEvent e) { }
}
我希望输出为。
*(播放器和硬币)两个线程都可以在侦听器上正常工作。