【发布时间】:2013-12-02 03:30:39
【问题描述】:
我正在尝试使用 Swing 构建一个简单的问答游戏。用户应该能够从组合框中挑选水果或蔬菜,并猜测它是水果还是蔬菜。如果他们猜对了,GUI 应该输出“yes”。如果他们猜错了,它应该输出“no”。代码似乎编译正确,但运行不正确。
我在“水果”和“蔬菜”按钮的 ActionListener 中使用了 if-else 循环,以确定用户是否猜对了。
public class GUI {
public static String input;
public static void main(String[] args) {
new GUI();
}
public GUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Simple GUI");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
final String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
final String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
String[] combined = {"Apple", "Apricot", "Banana"
,"Cherry", "Date","Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish","Kiwi", "Orange", "Pear", "Strawberry", "Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery","Shallot", "Spinach", "Swede"
, "Turnip"};
JPanel comboPanel = new JPanel();
JLabel comboLabel = new JLabel("Is it a Fruit or Vegetable?:");
final JComboBox fruitsVeggies = new JComboBox(combined);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = (String) fruitsVeggies.getSelectedItem();
}
};
fruitsVeggies.addActionListener(actionListener);
comboPanel.add(comboLabel);
comboPanel.add(fruitsVeggies);
final JButton fruitButton = new JButton( "Fruit");
JButton vegButton = new JButton("Vegetable");
final JLabel yes = new JLabel("YES");
final JLabel no = new JLabel("NO");
ActionListener listener = new ActionListener()
{
public void actionPerformed (ActionEvent d)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
{
yes.setVisible(true);
}
else
no.setVisible(true);
}
}
};
ActionListener vegListener = new ActionListener()
{
public void actionPerformed(ActionEvent f)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
{
no.setVisible(true);
}
else
yes.setVisible(true);
}
}
};
no.setVisible(false);
yes.setVisible(false);
fruitButton.addActionListener(listener);
vegButton.addActionListener(vegListener);
frame.add(comboPanel, BorderLayout.NORTH);
frame.add(vegButton,BorderLayout.WEST);
frame.add(fruitButton, BorderLayout.EAST);
frame.add(yes, BorderLayout.CENTER);
frame.add(no, BorderLayout.CENTER);
frame.setVisible(true);
}
}
【问题讨论】:
-
那么具体是什么问题?您所说的只是“它没有正确运行”。输出是否与您的预期不同?哪些输入是这种情况?
-
请对代码、输入/输出和结构化文档(如 HTML 或 XML)使用代码格式。为此,请选择示例并单击消息发布/编辑表单上方的
{}按钮。 -
只是一个建议:使用一个 JLabel 和
setText()方法来更改输出。
标签: java swing actionlistener