gpt4 book ai didi

java - 向主 java 发送事件

转载 作者:行者123 更新时间:2023-12-01 23:09:15 25 4
gpt4 key购买 nike

我有一个CountDownTimer类,当它完成倒计时时,它应该向主java(或任何使用它的类)分派(dispatch)一个事件,让它知道它已经完成。

这是我的类(class):

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;

public class CountTimer {

private Label targetText;
private String direction;
private int minutes;
private int seconds;
private int totalSeconds;
private int timeTotal;
private int timeLoaded;
private Boolean test;

Timer timer;


public CountTimer(int min,int sec,String dir,Label targetTextField)
{
minutes = min * 60;
seconds = sec;
timeTotal = minutes + seconds;
if (dir == "down") {
totalSeconds = minutes + seconds;
}
else {
totalSeconds = 0;
}
if (targetTextField != null) {
targetText = targetTextField;
}
direction = dir;
}

public void start()
{
timer = new Timer(){
public void run(){
timeLoaded += 1;

if (direction == "up") {
totalSeconds++;
}
else {
totalSeconds--;
}

seconds = totalSeconds % 60;
minutes = (int) Math.floor(totalSeconds / 60);
String minutesDisplay = (minutes < 10) ? "0" + Integer.toString(minutes) : Integer.toString(minutes);
String secondsDisplay= (seconds < 10) ? "0" + Integer.toString(seconds): Integer.toString(seconds);
if (targetText != null) {
targetText.setText( minutesDisplay + ":" + secondsDisplay);
}
if (test=true) {
consoleLog(minutesDisplay + ":" + secondsDisplay);
}

if(timeTotal == timeLoaded) {
//DISPATCH CUSTOM EVENT TO MAIN.JAVA HERE
Window.alert("OK");
timer.cancel();
}
}
};

timer.scheduleRepeating(1000);
}

public int getTimeTotal()
{
return timeTotal;
}

public int getTimeLoaded()
{
return timeLoaded;
}

public int getProg()
{
return (int) Math.floor(timeLoaded/timeTotal*100);
}

public native final void consoleLog(String msg)/*-{
console.log(msg);
}-*/;

}

请帮忙,我该怎么做?

最佳答案

我相信您正在寻求实现发布-订阅模式。 http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern

您可以允许订阅者在您的对象上注册。一旦您完成操作,它就可以通知订阅者操作​​已完成。

示例:

public interface Subscriber {
public void notify();
}

public class Publisher {
private ArrayList<Subscriber> subscribers = new ArrayList<>();

public void addSubscriber(Subscriber s) {
subscribers.add(s);
}

public void doWork() {
System.sleep(100);
notifyAll();
}

private void notifyAll() {
for(Subscriber s : subscribers) {
s.notify();
}
}
}

关于java - 向主 java 发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22273221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com