我正在嘗試將應用程序從 python(使用 TKinter)翻譯成 Java。Tkinter 有一個循環機制,例如:<!-- language: python -->def checkState(): if checkCond1(): root.after_idle(cond1Loop) elif checkCond2(): root.after_idle(cond2Loop) elif checkCond3(): root.after_idle(cond3Loop) else: print('not found known state...') root.update_idletasks() # waits for idle Tk tasks root.after_idle(checkState)def cond1Loop(): # some checks here, may be looping deeper root.after_idle(cond1Loop)def cond2Loop(): # some checks here, may be looping deeper root.after_idle(cond2Loop)def cond3Loop(): # some checks here, may be looping deeper root.after_idle(cond3Loop)root = Tk()mainWindow = Frame(root)# some win init hereroot.after_idle(checkState)# calls function when no idle tasksroot.mainloop()我的第一次嘗試是使用定時器來實現它,但不能從它自己的函數中停止定時器:<!-- language: java-->private void mainLogicLoop(){ javax.swing.Timer localtimer = new javax.swing.Timer(100, e -> { //finding state if(checkCond1()){ System.out.println("I am at cond 1."); cond1Loop(); //here i need to stop this timer, //but localtimer is invisible from here. //cond1Loop() will run its own timer... }else if(checkCond2()){ System.out.println("I am at cond 2."); cond2Loop(); //here i need to stop this timer, //but localtimer is invisible from here. //cond2Loop() will run its own timer... }else if(checkCond3()){ System.out.println("I am at cond 3."); cond3Loop(); //here i need to stop this timer, //but localtimer is invisible from here. //cond3Loop() will run its own timer... }else{ System.out.println("No known conditions found."); } localtimer.start();}public static void main(String[] args) { mainLogicLoop();}
1 回答

心有法竹
TA貢獻1866條經驗 獲得超5個贊
這個循環機制很容易使用 ExecutorService 實現。工作代碼示例:在構造函數中我創建服務ExecutorService service = Executors.newCachedThreadPool();
并在每個循環結束時調用 service.submit(() -> loopname());
添加回答
舉報
0/150
提交
取消