最近开始尝试写Java游戏,发现Thread。sleep会使所有线程暂停,怎么处理呢
packagetu;importjava.awt.Color;importjava.awt.Graphics;importjava.awt.event.KeyEvent;...
package tu;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class tu extends JFrame{
renwu bashen = new renwu();
public void shows() {
setBackground(Color.white);
setBounds(160, 100,700,500);
setVisible(true);
new PaintThread().start();
new keyThread().start();
}
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, 700, 500);
}
g.drawImage(bashen.img, bashen.x,bashen.y, null);
}
class keyThread extends Thread{
/**
* 事件监听
* */
public void run() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == 'w'){
for (int i = 1; i < 4; i++) {
bashen.img = GameUtil.getImage("images/t"+(i+1)+".bmp");
bashen.y -= 20;
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
});
}
}
class PaintThread extends Thread{
/**
* 内部类定义重画类,方便调用外部类
* */
public void run() {
while(true){
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
tu sTu =new tu();
sTu.shows();
}
protected static void PaintThread() {
}
}
在事件操作中用到线程暂停,但是其他线程也暂停了,就不能重绘了T.T 展开
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class tu extends JFrame{
renwu bashen = new renwu();
public void shows() {
setBackground(Color.white);
setBounds(160, 100,700,500);
setVisible(true);
new PaintThread().start();
new keyThread().start();
}
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, 700, 500);
}
g.drawImage(bashen.img, bashen.x,bashen.y, null);
}
class keyThread extends Thread{
/**
* 事件监听
* */
public void run() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == 'w'){
for (int i = 1; i < 4; i++) {
bashen.img = GameUtil.getImage("images/t"+(i+1)+".bmp");
bashen.y -= 20;
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
});
}
}
class PaintThread extends Thread{
/**
* 内部类定义重画类,方便调用外部类
* */
public void run() {
while(true){
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
tu sTu =new tu();
sTu.shows();
}
protected static void PaintThread() {
}
}
在事件操作中用到线程暂停,但是其他线程也暂停了,就不能重绘了T.T 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询