我试图让组合框中的选定值显示在提示窗口中,但提示窗口出现两次。我没有复制任何代码,但为什么会这样?
代码段: -
package interfaceGUI;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class BirthdayForm extends JFrame{
private JLabel chooseItem;
private JLabel chooseQuantity;
private JComboBox items;
private JTextField quantity;
private JTextArea selection;
private JButton Rent;
private JButton Edit;
private JButton Cancel;
private JPanel choose;
private JPanel forButton;
private String list[] = {"Chair", "Napkin", "Garland", "Mirrored Ball",
"Floral Vases", "Large Balloons", "Square Jars"};
public BirthdayForm()
{
super("Birthday Party Supplies Rental Form");
setLayout(new FlowLayout());
chooseItem = new JLabel("Choose Item:");
items = new JComboBox(list);
chooseQuantity = new JLabel("Choose Quantity:");
quantity = new JTextField(5);
choose = new JPanel();
choose.setLayout(new GridLayout(1,4));
choose.add(chooseItem);
choose.add(items);
choose.add(chooseQuantity);
choose.add(quantity);
add(choose);
selection = new JTextArea(15,30);
add(selection);
Rent = new JButton("Rent");
Edit = new JButton("Edit List");
Cancel = new JButton("Cancel");
forButton = new JPanel();
forButton.setLayout(new GridLayout(1,3));
forButton.add(Rent);
forButton.add(Edit);
forButton.add(Cancel);
add(forButton);
comboHandler handler = new comboHandler();
items.addItemListener(handler);
}
public class comboHandler implements ItemListener
{
public void itemStateChanged(ItemEvent event)
{
if(event.getSource() == items)
{
String item = (String) items.getSelectedItem();
if(item == "Chair")
{
JOptionPane.showMessageDialog(null, "Chair" , "Items",
JOptionPane.INFORMATION_MESSAGE);
}
}
else
{
}
}
}
}
我做错了什么?我无法找到我的错误。请帮忙。
答案 0 :(得分:3)
以下是您需要的更改,请检查项目是否已选中,
public void itemStateChanged(ItemEvent event)
{
if(event.getSource() == items)
{
int state = event.getStateChange();
if(state == ItemEvent.SELECTED)
{
String item = (String) items.getSelectedItem();
JOptionPane.showMessageDialog(null, item , "Items", JOptionPane.INFORMATION_MESSAGE);
}
}
else
{
}
}