我是新來的java,我有一個問題。我可以讓我的形狀在全部四個方向上移動,但是我無法停止線程,因此形狀只能朝一個方向移動。此外,我要畫形狀後面的一條線(TRON認爲光周期的),但我不能確定怎麼做...如何停止鍵處理程序中的線程
package test;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Test extends JPanel implements KeyListener {
int x = Test.WIDTH/2;
int y = Test.HEIGHT/2;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d;
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillRect(x, y, 10, 10);
}
private void moveleft() {
new Thread (new Runnable()
{
public void run()
{
while(true)
{
x = x - 1;
repaint();
//System.out.println("Right");//For debugging purposes
try {
Thread.currentThread().sleep(6);
} catch (Exception e){}
if(!true)
break;
}
}
}).start();
}
private void moveright() {
new Thread (new Runnable()
{
public void run()
{
while(true)
{
x = x + 1;
repaint();
//System.out.println("Right");//For debugging purposes
try {
Thread.currentThread().sleep(6);
} catch (Exception e){}
if(!true)
break;
}
}
}).start();
}
private void moveup() {
new Thread (new Runnable()
{
public void run()
{
while(true)
{
y = y - 1;
repaint();
//System.out.println("Right");//For debugging purposes
try {
Thread.currentThread().sleep(6);
} catch (Exception e){}
if(!true)
break;
}
}
}).start();
}
private void movedown() {
new Thread (new Runnable()
{
public void run()
{
while(true)
{
y = y + 1;
repaint();
//System.out.println("Right");//For debugging purposes
try {
Thread.currentThread().sleep(6);
} catch (Exception e){}
if(!true)
break;
}
}
}).start();
}
public void keyPressed(KeyEvent e) {
//System.out.println("keyPressed");
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
//D.start();
moveright();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
moveleft();
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
movedown();
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
moveup();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped");
}
public Test() {
//this=new maindraw();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("BMTRON");
Test game = new Test();
frame.add(game);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
不要使用布爾文字,'while(true)'。爲什麼不使用可以由用戶更改的易變布爾變量?此外,只要可行,您應該更喜歡KeyListeners上的Key Bindings。 –