簡體   English   中英

設置后,Java單例檢索局部變量始終為null

[英]Java singleton retrieving local variable always null after setting

有一個問題真的讓我感到震驚。 因此,我們有一個MainView在其上顯示地圖(MapView是JComponent)。 在MapView類中,我們重寫paintComponent(Graphics g)來繪制我們的自定義內容。 到目前為止工作正常。

我們還有一個RouteControl單例類,其中包含一個局部變量Route,我們可以使用setRoute進行設置並使用getRoute進行檢索。 現在有趣的部分:

在我們的MapView paintComponent中檢索RouteControl實例時,Route始終為null。 但是我們已經在MainView中設置了一條路由,如果我們在設置完之后獲取了路由,則該路由不能為null。

我是否想念像多線程這樣的關鍵點? 我還有一個具有get / setMap的單例類MapControl,它可以正常工作。

要投影的代碼:

public class MainView extends javax.swing.JFrame {
    private static MainView instance;

    private void comboRouteActionPerformed(java.awt.event.ActionEvent evt) {
        File _routeFile = RouteControl.getInstance().getRouteFile(comboRoute.getSelectedItem().toString());
        Route _route = RouteControl.getInstance().loadRoute(_routeFile);
        RouteControl.getInstance().setRoute(_route);
        // if we retrieve the route here it works
    }
}

現在,MapView:JComponent:

public class MapView extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // this nicely works, also set in the MainView!
        if(MapControl.getInstance().getMap() != null) {
            BufferedImage mapImage = MapControl.getInstance().getMap().getMapImage();
            g.drawImage(mapImage, 0, 0, null);   

            // draw le route THIS IS ALWAYS NULL
            if(RouteControl.getInstance().getRoute() != null) {
                g.setColor(Color.red);
                g.fillRect(40, 40, 15, 15);
            }
            else {
                System.out.println("**** route is null");
            }
        }
    }
}

RouteControl:

public class RouteControl {
    private static RouteControl instance;
    private Route route;

    public static synchronized RouteControl getInstance() {
        if (instance == null) {
            instance = new RouteControl();
        }
        return instance;
    }    

    public Route getRoute() {
        return route;
    }

    public void setRoute(Route route) {
        System.out.println("RouteControl:setRoute");
        this.route = route;
    }
}

我認為您可能在這里有時間問題 好像您是從MainView類中的某處加載路由,並在加載后進行設置。 如果在加載完成之前繪制了MapView ,則路線將為null

您可以在此處輸入完整的代碼嗎?

像下面的調用這樣的調用會導致編譯錯誤,因此必須有更多的選擇。

  • 文件_routeFile = RouteControl.getInstance()。getRouteFile(comboRoute.getSelectedItem()。toString());
  • 路線_route = RouteControl.getInstance()。loadRoute(_routeFile);

我對單例布線錯誤的第一個猜測是類加載問題。 請檢查單例對象在物理上是否相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM