SWT Button SelectionListener called twice

时间:2017-08-04 13:07:32

标签: java swt

I use the same widgets on to display different "views" in the same window. To navigate between the views I use the same "next" button, I only change the listeners that load the next view. And the first time when I click the button it activates two concecutive listeners.

I will try to explain in more detail. The method that loads the first view removes "next" button's listener if there is one (normally there isn't). Then it creates the listener that would load the second view and adds it to the next button. The second view removes the listener and creates and adds a new one that would load the third view when the button is clicked.

So when I load the window and I click "next" button on the first view I have the third view loaded. The worst part is that when I click "back" button the load views in the reverse order and I start again from view one, it works perfectly without skipping the second view.

Here's the code:

private Button btnNext;

private SelectionListener nextListener;

private void loadFirstView(){
    if (nextListener != null) {
        btnNext.removeSelectionListener(nextListener);
    }

    nextListener = new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent event) {

            loadSecondView();

        }

        @Override
        public void widgetDefaultSelected(SelectionEvent event) {

        }
    };
    btnNext.addSelectionListener(nextListener);
 }


private void loadSecondView(){
    if (nextListener != null) {
        btnNext.removeSelectionListener(nextListener);
    }

    nextListener = new SelectionListener() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                loadThirdView();
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent event) {

            }
        };
    btnNext.addSelectionListener(nextListener);
}

private void loadThirdView(){
    if (nextListener != null) {
        btnNext.removeSelectionListener(nextListener);
    }

    System.out.println("third view is loaded :(");

}

2 个答案:

答案 0 :(得分:0)

我的猜测是因为这里正在进行的操作流程。 单击按钮,使其处于选中状态。在此状态期间,它调用load第二个视图,在该视图中设置新的侦听器。 我相信新的监听器会被调用,因为按钮仍处于被选中状态,或者尚未解析。

编辑:如果您说的是真的,我会很想看到您的后退按钮的代码

答案 1 :(得分:0)

这可能是我当地的问题 - 我仍然无法弄清楚为什么两个听众在一次点击后连续被解雇,但我发现(不是很优雅的解决方案)来解决这个问题:

因为使用具有相同event.time值的事件触发了两个侦听器,所以我在第一个视图中创建了一个字段eventTime并在nextButton的侦听器中设置了它的值为event.time然后在第二个视图的监听器中检查

if (!(event.time == eventTime)) {
    loadThirdView();
}
相关问题