ItemListener未检测到JCombobox选择更改并进行必要的更改

时间:2013-11-19 02:21:37

标签: java jframe actionlistener jcombobox itemlistener

我正在开发一个练习应用程序,而且我是JFrame的新手。我不完全确定我在这里缺少什么..我知道我需要在某个地方引用itemStateChanged,但我不确定哪个地方最合适。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class DebugFourteen3 extends JFrame implements ItemListener
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
   super("Pizza List");
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLayout(flow);
   pizzaBox.addItemListener(this);
   add(toppingList);
   pizzaBox.addItem("cheese");
   pizzaBox.addItem("sausage");
   pizzaBox.addItem("pepperoni");
   pizzaBox.addItem("onion");
   pizzaBox.addItem("green pepper");
   pizzaBox.addItem("green olive");
   pizzaBox.addItem("black olive");
   add(pizzaBox);
   add(aLabel);
}
public static void main(String[] arguments)
{
   JFrame frame = new DebugFourteen3();
   frame.setSize(200, 150);
   frame.setVisible(true);
}


public void itemStateChanged(ItemEvent[] list)
{
 Object source = list.getSource();
 if(source == pizzaBox)
 {
    int pizzaNum = pizzaBox.getSelectedIndex();
    totalPrice = pizzaPrice[pizzaNum];
    output = "Pizza Price $" + totalPrice;
    totPrice.setText(output);
  }
}
}

1 个答案:

答案 0 :(得分:0)

itemStateChanged需要ItemEvent arg,而不是数组

public void itemStateChanged(ItemEvent[] list)

应该是

public void itemStateChanged(ItemEvent e)

此外,将侦听器添加到Combobox并检测选择更改的正确方法是使用ActionListener。你应该省略itemStateChanged()并使用它。

public class DebugFourteen3 extends JFrame implements {

    ...

    public DebugFourteen3()
    {
        ...
        pizzabox.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                int pizzaNum = pizzaBox.getSelectedIndex();
                totalPrice = pizzaPrice[pizzaNum];
                output = "Pizza Price $" + totalPrice;
                totPrice.setText(output); 
            }
        });
    }

    ...
}