有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:getSelectedItem()未定义类型字符串

我的java程序有问题,我正在尝试使用JComboBox和JButton获取if语句的一些信息。问题是。getSelectedItem()未定义,我不知道该怎么办。 以下是组合框:

static String JCBDestinations, JCBNights, JCBAccomodation;
static String[] places, nights, stay;

//Destination drop down menu
    String[] JCBDestinations = { " ", "Paris", "Crete", "Croatia"};
    JComboBox places = new JComboBox(JCBDestinations);
    places.setSelectedIndex(4);
    places.addActionListener(this);

//Number of nights radio buttons
    String[] JCBNights = { " ", "7", "10", "14"};
    JComboBox nights = new JComboBox(JCBNights);
    nights.setSelectedIndex(4);
    nights.addActionListener(this);

//Accommodation type drop down menu
    String[] JCBAccomodation = {" ", "Hotel", "Villa", "Youth Hostel", "Bed & Breakfast"};
    JComboBox stay = new JComboBox(JCBAccomodation);
    stay.setSelectedIndex(4);
    stay.addActionListener(this);

//Find deal button
    JBFind = new JButton("Find Deal"); //Adding option 1 button
    window.add(JBFind);
    JBFind.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {

        }
    });

以下是If声明:

public void actionPerformed(ActionEvent e) 
{

    if (e.getSource() == JBFind);
    {
        System.out.println("Calculating cost");

        JLBeforeVAT.setText("£499");
        JTAfterVAT.setText("£589");
    }   
            if (JCBDestinations.getSelectedItem().equals("Paris"))
            {
                if (JCBNights.getSelectedItem().equals("7"))
                {
                    if (JCBAccomodation.getSelectedItem().equals("Hotel"))
                    {
                        JLBeforeVAT.setText("£499");
                        JTAfterVAT.setText("£589");
                    }

                }

            }
}

共 (1) 个答案

  1. # 1 楼答案

    错误信息准确地告诉你你做错了什么,所以这里的关键是仔细阅读它,并修复它所显示的错误。您可以从JComboBox中获得选择,而不是从字符串数组中。组合框变量名为places。所以

    if (places.getSelectedItem().equalsIgnoreCase("Paris"))
    

    其他问题:

    String[] JCBNights = { " ", "7", "10", "14"};
    JComboBox nights = new JComboBox(JCBNights);
    nights.setSelectedIndex(4);  // *****
    nights.addActionListener(this);
    

    当选定的索引仅上升到3:0、1、2、3时,您将其设置为4