【问题标题】:ItemListener not detecting JCombobox selection change and making necessary changesItemListener 未检测到 JCombobox 选择更改并进行必要的更改
【发布时间】:2013-11-19 02:21:37
【问题描述】:

我正在开发一个练习应用程序,而且我是 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);
  }
}
}

【问题讨论】:

    标签: java jframe actionlistener jcombobox itemlistener


    【解决方案1】:

    itemStateChanged 采用 ItemEvent 参数,而不是数组

    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); 
                }
            });
        }
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      相关资源
      最近更新 更多