我正在制作格斗游戏,玩家将选择其类别。我怎么说If(玩家选择战士)然后(等等)用我的代码?
import java.awt.GridLayout;
import javax.swing.*;
public class ButtonTest {
static JDialog dialog;
public static void main(String[] args) {
JDialog dialog = null;
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("Choose Your Class!");
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
String[] buttonTxt = {"Warrior","Battlemage","Tank","Archer","Kitty"};
JButton[] buttons = new JButton[buttonTxt.length];
for (int i = 0; i < buttonTxt.length; i++)
{
buttons[i] = new JButton(buttonTxt[i]);
panel.add(buttons[i]);
}
optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
optionPane.add(panel);
dialog = optionPane.createDialog(null, "Icon/Text Button");
dialog.setVisible(true);
}
}
答案 0 :(得分:0)
您可以对所有按钮使用actionperformed事件。
for (int i = 0; i < buttonTxt.length; i++){
buttons[i] = new JButton(buttonTxt[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
onClickButton(buttonTxt[i]);
}
});
panel.add(buttons[i]);
}
将 buttonTxt 设为最终变量。 然后你可以在 onClickButton()
中写下你的if语句private void onClickButton(String buttonText){
if(buttonText.equals("Warrior")){
//do your stuff
}
}