我是一个新的程序员,我正在使用下拉框(选择)作为输入设备的文本冒险工作。我在第一个盒子上有一个itemListener,它使用可以添加的成员填充第二个成员。然后允许玩家点击提交按钮,第一个框被重置为列表中的第一个项目,第二个框应该被清除。当我运行该程序时,第一次完全按照计划进行反应。第二次尝试使用下拉框输入内容时,下拉框不响应。我在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
请给更多代码,或者更多详细信息 – Khinsu
好的,我会尽力给出更多有用的信息。我假设应该发生的事情是,itemListener应该在每次更改下拉框的状态时触发,但由于某种原因它不会。这一点很显然,System.out.println不会在我每次选择commandDropDown时显示。我很抱歉,如果这不是您要查找的信息,我不确定其他信息对您有用。 – Sharpx
为了更快得到更好的帮助,请发布[SSCCE](http://sscce.org/)。 –