Java-如何;刷新“;键事件,并在while循环中再次调用它
问题并不像我将要描述的那么简单,但范例有点类似。所以,假设我用while循环创建了这个方法,只要x<100,它就会一直运行。只有按下空格键,x才会增加1。我到底要怎么做 我写的是:Java-如何;刷新“;键事件,并在while循环中再次调用它,java,actionlistener,keyevent,Java,Actionlistener,Keyevent,问题并不像我将要描述的那么简单,但范例有点类似。所以,假设我用while循环创建了这个方法,只要x{ while(x.get()
public void keyPressed(String key){
//assume that x = 0
while(x < 100){
if(key.equals("Space")){
x += 1;
}
}
}
循环必须在与侦听KeyEvent的线程不同的线程中运行。 调用KeyEvent侦听器时,必须更改另一个类中的属性,以便线程可以在循环的每个迭代中测试它
import java.util.concurrent.atomic.AtomicInteger;
public class MainLoop {
private final AtomicInteger x = new AtomicInteger(0);
public void startLoop() {
Runnable runnable = () -> {
while (x.get() < 100) {
// Do stuff...
}
};
// start the thread
new Thread(runnable).start();
}
public void keyPressed(String key) {
if (key.equals("Space")) {
x.incrementAndGet();
}
}
}
public class KeyListener {
public void keyPressed(KeyEvent e) {
String key = KeyEvent.getKeyText(e.getKeyCode());
for (GameObject go : gameobjects) {
go.keyPressed(key);
}
}
}
导入java.util.concurrent.AtomicInteger;
公共类主循环{
私有最终AtomicInteger x=新的AtomicInteger(0);
public-void-startoop(){
Runnable Runnable=()->{
while(x.get()<100){
//做些事情。。。
}
};
//开线
新线程(runnable.start();
}
按下公共无效键(字符串键){
if(key.equals(“空格”)){
x、 递增和获取();
}
}
}
公共类密钥侦听器{
按下公共无效键(按键事件e){
字符串key=KeyEvent.getKeyText(例如getKeyCode());
用于(游戏对象转到:游戏对象){
go.按键(按键);
}
}
}
请注意,线程之间共享的属性必须是线程安全的(对于字符串,可以使用java.util.concurrent.atomic包中的AtomicReference类)
要管理线程,最好使用JDK线程执行器这看起来像是要创建一个游戏。你使用某种框架吗?
import java.util.concurrent.atomic.AtomicInteger;
public class MainLoop {
private final AtomicInteger x = new AtomicInteger(0);
public void startLoop() {
Runnable runnable = () -> {
while (x.get() < 100) {
// Do stuff...
}
};
// start the thread
new Thread(runnable).start();
}
public void keyPressed(String key) {
if (key.equals("Space")) {
x.incrementAndGet();
}
}
}
public class KeyListener {
public void keyPressed(KeyEvent e) {
String key = KeyEvent.getKeyText(e.getKeyCode());
for (GameObject go : gameobjects) {
go.keyPressed(key);
}
}
}