我编写这段代码是为了做出用户选择游戏模式时必须做出的选择:
JButton btnNewButton = new JButton("Start Game");
JRadioButton beginner = new JRadioButton("Beginner");
JRadioButton intermedie = new JRadioButton("Intermedie");
JRadioButton expert = new JRadioButton("Expert");
JRadioButton custom = new JRadioButton("Custom");
JRadioButton mineFullRandom = new JRadioButton("Mine full random");
JRadioButton minePartialRandom = new JRadioButton("Mine partial random");前三个用来选择游戏的难度,最后两个用来选择游戏的模式。我刚设置了初学者难度和我的完全随机modality.The Start Game按钮,因为您可以从名字中了解开始游戏的必要性。
一旦我创建了JRadioButton和JButton,我将把它们添加到GroupLayout上。
Controller.java
这门课我想要处理所有的按钮事件。
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
JRadioButton difficulty = (JRadioButton)e.getSource();
JRadioButton choice = (JRadioButton)e.getSource();
if(source.getText().equals("Start Game")){
if(difficulty.getText().equals("Beginner") /*&& choice.getText().equals("Mine full random")*/){
fullRandom = new FullRandomGrid(ROW_BEGINNER, COLUMN_BEGINNER, MINE_BEGINNER);
View view = new View(fullRandom);
//Minesweeper.game.container.add(view);
/*Minesweeper.game.container.add(new View(fullRandom), BorderLayout.CENTER);
Minesweeper.game.container.remove(Minesweeper.menu);
Minesweeper.game.setVisible(true); */
view.setVisible(true);
}
else if(difficulty.getText().equals("Beginner") && choice.getText().equals("Mine partial random")){
partialRandom = new PartialRandomGrid(ROW_BEGINNER, COLUMN_BEGINNER, MINE_BEGINNER);
Minesweeper.game.container.add(new View(partialRandom));
Minesweeper.game.container.remove(Minesweeper.menu);
}
else if(difficulty.getText().equals("Intermedie") && choice.getText().equals("Mine full random")){
fullRandom = new FullRandomGrid(ROW_INTERMEDIE, COLUMN_INTERMEDIE, MINE_INTERMEDIE);
}
else if(difficulty.getText().equals("Intermedie") && choice.getText().equals("Mine partial random")){
partialRandom = new PartialRandomGrid(ROW_INTERMEDIE, COLUMN_INTERMEDIE, MINE_INTERMEDIE);
}
}
}当您选择一个特定的JRadioButton时,您是否取消了先前选择的那个?当按下“开始游戏”按钮时,如何启动游戏并关闭菜单?
发布于 2017-06-17 22:06:53
您可能面临的问题是,您通过ActionListener事件获得的源将在整个源代码、难点和 source 中相同。首先,您应该有一个组来存储单选按钮:
ButtonGroup difficultyGroup = new ButtonGroup();当将JRadioButtons添加到此组时,选择一个选项将自动取消选择所有其他选项:
difficultyGroup.add(beginner);
difficultyGroup.add(intermediate);
difficultyGroup.add(expert);
...这确保一次只选择一个按钮。,围绕着收到的事件来讨论这个问题-
向每个单选按钮添加一个ActionCommand将允许您通过分配给每个按钮的字符串对按钮执行操作。例如,在将按钮添加到组之前,请分配以下值:
beginner.addActionCommand("Beginner");
intermediate.addActionCommand("Intermediate");请记住,以下字符串仅用于内部目的。这意味着您可以通过指定的String值来识别按钮。
public void ActionPerfomed(ActionEvent e) {
// To get the source (for the game start button)
JButton source = (Jbutton) e.getSource();
// Get the radio button source which was selected
// Resultantly obtain the String which it represents
String difficulty = difficultyGroup.getSelection().getActionCommand();
}现在,您可以在条件difficulty语句中使用String变量来安全地执行这些操作。
希望这有所帮助:)
https://stackoverflow.com/questions/44608009
复制相似问题