gpt4 book ai didi

java - 在继续之前等待 Java Swing 中的按钮被按下?

转载 作者:行者123 更新时间:2023-12-02 03:36:14 26 4
gpt4 key购买 nike

所以我有这个 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);
}

这只是创建一个项目列表和一个按钮。单击按钮时,它将获取所选项目并将其返回到 Controller 以进行处理(对于我们的项目,它会更改玩家的神奇宝贝)。

 */
@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 与 Controller 实际上没有任何关系。我只是想确保它现在可以得到选择。但是,在等待做出选择之前,我在其余代码方面遇到了麻烦。

我认为 Java 中的 Swing 和输入通常应该暂停并等待输入,然后再继续处理其余代码。但是,现在它运行时会打开选择菜单,然后在 Controller 中将选定的神奇宝贝设置为空。我考虑过添加一个 while 循环来等待并解决这个问题,但我觉得 Swing 中有一种更简单的方法可以做到这一点。

有没有办法让我的代码的其余部分等待,直到选择按钮并处理操作?

提前致谢。

最佳答案

使用JOptionPane。它将为您构建模式对话框和按钮。模态对话框将停止执行,直至关闭。

阅读 Swing 教程中关于 How to Make Dialogs 的部分了解更多信息和工作示例。

add("Center", centerPanel);

不要使用“魔法”值。 API 将定义应使用的值。这也不是向容器添加组件的方法。相反,您应该使用:

add(centerPanel, BorderLayout.CENTER);

关于java - 在继续之前等待 Java Swing 中的按钮被按下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552149/

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