本学期我刚开始使用Java,现在正在开展一个小组项目。我创建了下拉菜单,但现在我需要选择用户选择的选项并将它们传递给另一个类。我已经尝试使用ActionListener
(你会看到注释掉的),但后来我认为我并不真的需要它,因为它是radiobuttons而我可以使用.isSelected()
代替。
你能帮助我理解发生了什么以及我应该如何进行预期的变量传递?先感谢您。请参阅以下代码:
public class GameMenu extends JFrame
{
String animal;
JRadioButtonMenuItem dog;
JRadioButtonMenuItem cat;
JMenuBar menuBar;
JMenu menu;
JMenu animalOptions;
public GameMenu()
{
setTitle("The Most Fun Game Ever");
setSize(800, 800);
menuBar = new JMenuBar();
//Adds menubar to the JFrame
setJMenuBar(menuBar);
//Define and add drop down menu to menubar
menu = new JMenu("Game Options");
menuBar.add(menu);
//Create and add radio button items and set their accelerators
dog = new JRadioButtonMenuItem("Dog");
cat = new JRadioButtonMenuItem("Cat");
//Define each button group and add items to each group.
ButtonGroup animalGroup = new ButtonGroup();
animalGroup.add(dog);
animalGroup.add(cat);
//Define 4 submenus for the main menu items & set Mnemonics
animalOptions = new JMenu("Animal Options");
//Add items to the submenus
animalOptions.add(dog);
animalOptions.add(cat);
//Add a listener to the menu items
//dog.addActionListener(new ActionListener()
//{
// public void actionPerformed(ActionEvent arg0)
// {
// animal = "tiger-dog.jpg";
// }
//});
}
public String getAnimal()
{
if (dog.isSelected())
{
animal = "tiger-dog.jpg";
}
else if (cat.isSelected())
{
animal = "bruteforce-cat.jpg";
}
return animal;
}
public static void main(String[] args)
{
GameMenu test = new GameMenu();
String animalChoice = test.getAnimal();
System.out.println(animalChoice);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
}