簡體   English   中英

在繼續之前等待在Java Swing中按下按鈕?

[英]Waiting for a button to be pressed in Java Swing before moving on?

所以我有這個GUI

public ChangePokemonView(Controller c)
{
    this.controller = c;
    this.currentBattleEnvironment = currentBattleEnvironment.getInstance();
    populateInactivePokemon(); //REMOVE LATER REMOVE LATER  REMOVE LATER  REMOVE LATER  REMOVE LATER 
    this.pokemonList = new JList(inactivePlayerPokemon);
    pokemonList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Only one thing can be selected at a time.
    this.pokemonLabel = new JLabel("Choose your Pokemon!");
    this.confirmSelection = new JButton("Confirm Selection");
    this.confirmSelection.addActionListener(this);

    setLayout(new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Closes GUI window when close, may need to change later
    JPanel centerPanel = new JPanel(new GridLayout(3, 1));
    centerPanel.add(pokemonLabel);
    centerPanel.add(pokemonList);
    centerPanel.add(confirmSelection);

    add("Center", centerPanel);
    pack();
    setVisible(true);
}

這只是創建一個項目列表和一個按鈕。 單擊該按鈕時,它將獲取所選項目並將其返回到控制器然后進行處理(對於我們的項目,它會更改玩家口袋妖怪)。

 */
@Override
public void actionPerformed(ActionEvent event)
{
    if (event.getSource() == confirmSelection)
    {
        this.pokemonSelected = (String) pokemonList.getSelectedValue();
        this.controller.setCurrentPokemon(this.pokemonSelected);
        //JOptionPane.showConfirmDialog(null, "You pressed: "+output); //USED FOR TESTING, THIS WILL OUPUT JUST THE NAME THAT WAS SELECTED
    }

}

setCurrentPokemon與控制器沒有任何關系。 我只是想確保它現在能夠得到選擇。 但是我在等待選擇的其余代碼時遇到問題。

我認為Swing和Java的輸入應該暫停並等待輸入,然后繼續使用其余的代碼。 但是,現在它運行打開選擇菜單,但然后在控制器中將選定的寵物小貓設置為null。 我想添加一個while循環來等待並解決這個問題,但我覺得有一個更容易的方法來構建Swing。

有沒有辦法,所以我可以讓我的其余代碼等到選擇按鈕並處理操作?

提前致謝。

使用JOptionPane 它將為您構建模態對話框和按鈕。 模態對話框將停止執行,直到關閉為止。

有關更多信息和工作示例,請閱讀有關如何創建對話框的Swing教程中的部分。

add("Center", centerPanel);

不要使用“魔法”值。 API將定義應使用的值。 這也不是向Container添加組件的方法。 相反,你應該使用:

add(centerPanel, BorderLayout.CENTER);

暫無
暫無

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

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