爲什麼我的組合框不執行我在ItemListener中聲明的事物?當我點擊組合框內的一個項目時,程序掛起,我需要關閉整個BlueJ。請大家看看什麼是錯在我的代碼ItemListener不起作用
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class HulaHoops {
private Scanner inp = new Scanner(System.in);
public static void main(String[]args) {
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new HulaHoops();
}
});
}
public HulaHoops() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
String choices[] = {"Shoes","Comb","Ball"};
JComboBox combo = new JComboBox(choices);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setVisible(true);
combo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e)
{
String item = (String)e.getItem();
if (e.getStateChange() == ItemEvent.SELECTED)
{
System.out.println("You chose " +item);
if (item == "Shoes")
{
System.out.println("Enter quantity: ");
int bilang = inp.nextInt();
int total = bilang * 99;
String order = bilang + " " + "Shoes " + " " + total;
System.out.print("" + order);
}
else if (item == "Comb")
{
System.out.println("Enter quantity: ");
int bilang = inp.nextInt();
int total1 = bilang * 99;
String order1 = bilang + " " + "Comb " + " " + total1;
System.out.print("" + order1);
}
else if (item == "Ball")
{
System.out.println("Enter quantity: ");
int bilang = inp.nextInt();
int total2 = bilang * 99;
String order2 = bilang + " " + "Ball " + " " + total2;
System.out.print("" + order2);
}
}
}
});
}
}
並總是不使用==比較字符串,而是使用equals()或equalsIgnoreCase()方法。 – 2013-03-06 17:08:51