簡體   English   中英

游戲循環期間無法吸引到JPanel

[英]Can't draw into JPanel during game loop

我試圖繪制在游戲循環中擴展JPanel的MapPanel,但失敗了。 但是,如果我在循環外部執行此操作,則會成功繪制。 這是我的相關代碼:

MenuPanel.java:

public void actionPerformed(ActionEvent e) {

    JButton pushedButton =(JButton) e.getSource();

    if(pushedButton == play)
        guiManager.setGamePanelVisible(true);
    else if(pushedButton == settings)
        guiManager.setSettingsPanelVisible();
    else if(pushedButton == credits)
        guiManager.setCreditsPanelVisible();
    else if(pushedButton == highScores)
        guiManager.setHighScoresPanelVisible();
    else if(pushedButton == help)
        guiManager.setHelpPanelVisible();

}

GUIManager.java:

...
    public void setGamePanelVisible(boolean gameStarted){
        GamePanel gp = new GamePanel(this);
        setContentPane(gp);
        gp.initiate();
    }
...

GamePanel.java

public void initiate(){
   this.gm = new GameManager(this);  // constructs the game manager and triggers the game loop 
}

GameManager.java

public GameManager(GamePanel gp) {
    this.gp = gp;
    this.run();
}

private void run(){
    while(running){
        draw();
        try{
            sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted at GameManager.java");
        }
    }

我的預測是,當MenuPanel仍然可見時(在setGamePanelVisible方法上),游戲循環開始,並且由於它永遠不會退出該方法,因此MenuPanel保持可見狀態,從而導致這種情況。 但是,我可能是錯的。 即使是問題所在,我也想不出任何解決方案。 也許我應該將按鈕偵聽器移到另一個類? 先感謝您!

您正在阻止事件分派線程,這會阻止UI更新。 EDT負責處理重塗請求等。 您的游戲循環是從EDT的上下文中運行的。

actionPerformed是在EDT中執行的,它調用setGamePanelVisible ,后者調用GameManager並調用run ,這會阻止...

有關更多詳細信息,請參閱Swing中的並發

Swing不是線程安全的,因此您不能簡單地啟動一個新的Thread並希望能夠解決所有問題,您需要確保對UI的所有更新(包括對UI可能需要的信息的更新)都是在內部進行的EDT的上下文

一種更簡單的解決方案是僅使用Swing Timer ,它將允許您安排在EDT上下文中執行的定期定時更新。 有關更多詳細信息,請參見如何使用Swing計時器

暫無
暫無

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

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