我在使用Item Listeners
时遇到了问题。这是我第一次使用它,到目前为止我只使用了Item Event
。我想知道你是否能弄清楚这两者之间的区别,并指出我做错了什么。
我的问题出现在第 46 行,该行开头为:Object source = toppingList.getSource();我得到的错误是“找不到符号”。
我认为我在 getSource();
之前使用了错误的项目,我认为 toppingList
是正确的项目,我看不到我可以将哪些其他元素放在它的位置。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pizza extends JFrame{
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 Pizza()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
pizzaBox.addItemListener((ItemListener) 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);
add(totPrice);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = toppingList.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
最佳答案
Gui 元素没有任何 getSource
,它是事件的一个方法 - 告诉您哪个 gui 元素生成了该事件。但您知道事件的来源是什么,因为您在构造函数中写道:
pizzaBox.addItemListener((ItemListener) this);
并且您没有将其添加到任何其他 gui 元素中。因此您无法从任何其他 gui 元素获取事件。所以不要对其进行测试。
但还有其他问题:
您的PizzaBox
应该实现ItemListener
:
public class Pizza extends JFrame implement ItemListener
然后就写
pizzaBox.addItemListener(this);
如果您想监听多个元素,请为每个元素添加单独的匿名监听器(Pizza 没有实现 ItemListener)
// in your constructor:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex(); // in your code you have int pizzaNum but at the same time, pizzaNum is a class variable, probably an error
// and so on
}
}
});
或者您可以将代码移至单独的方法
public class Pizza extends JFrame {
public Pizza() {
:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pizzaBox_itemStateChanged(e);
}
});
:
}
private void pizzaBox_itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex();
// and so on
}
}
:
}
关于java - 项目监听器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20042893/