在这里输入图像描述我是一个新的程序员,我正在进行文本冒险,使用下拉框(选项)作为输入设备。我在第一个框上有一个itemListener,它使用可以添加的成员填充第二个成员。然后允许玩家单击提交按钮,并将第一个框重置为列表中的第一个项目,并且应该清除第二个框。当我运行程序时,它第一次完全按照计划做出反应。我第二次尝试使用下拉框输入内容时,下拉框不响应。我在itemListener中放了一个标记,看看它是否甚至触发了它发现它不是。我觉得我已经以各种可想象的方式调整了程序,但我不知道是什么导致了这个问题。如果我在下拉框中的项目之间切换几次,则itemListener会再次开始响应。
这是我聚集在一起的问题的代表。
import java.awt.Choice;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class gui implements ActionListener
{
private static JTextPane outputField = new JTextPane();
private static JPanel mainPanel = new JPanel(new GridBagLayout());
private Choice commandDropDown = new Choice();
private Choice itemDropDown = new Choice();
private JButton submitButton = new JButton();
public gui()
{
JFrame frame = new JFrame("test");
mainPanel.setSize(450,585);
commandDropDown = buildCommandBox(commandDropDown);
commandDropDown.setBounds(100, 15, 100, 40);
itemDropDown.setBounds(200, 15, 100, 40);
submitButton.setText("submit");
submitButton.setBounds(15, 15, 100, 40);
submitButton.addActionListener(this);
frame.add(commandDropDown);
frame.add(itemDropDown);
frame.add(submitButton);
frame.setResizable(false);
frame.pack();
frame.setSize(300, 300);
//frame.setLayout(null);
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
itemDropDown.removeAll();
commandDropDown.select(0);
}
private Choice buildCommandBox(Choice custoChoi)
{
final Choice c = new Choice();
c.addItem("choices");
c.addItem("Option1");
c.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
System.out.println("the action event for the command"
+ "box is working.");
if(c.getSelectedItem().equals("Option1"))
{
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return c;
}
}
希望这些图片能够清除我对帖子的任何疑惑。 http://imgur.com/a/h9oOX#0
答案 0 :(得分:0)
在我看来,你的buildCommandBox( Choice custoChoi)
是错误的,应该是这样的:
private Choice buildCommandBox(final Choice custoChoi) {
custoChoi.addItem("choices");
custoChoi.addItem("Option1");
custoChoi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
System.out.println("the action event for the command" + "box is working.");
if (custoChoi.getSelectedItem().equals("Option1")) {
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return custoChoi;
}
如果允许Choice
,我建议您使用Swing
的{{3}}个时刻。