为什么我的程序没有找到试图从JComboBox中获取选择的getSelectedIndex()方法?

时间:2014-04-01 18:42:23

标签: java jcombobox itemlistener

我的程序没有找到符号getSelectedIndex()方法。我想知道它为什么找不到它以及如何解决这个问题。 这是错误:
错误:找不到符号
  symbol:方法getSelectedIndex()
  location:变量roomChoice类型java.lang.String []

这是我的代码:

import java.awt.*;  
import java.awt.event.*;  
import javax.swing.*;  

public class CottageRental2 extends JFrame implements ItemListener{
  // Declare all instance data  (primitives and objects used) 
  private int WIDTH = 676;
  private int HEIGHT = 321; 
  Container con; 
  private JLabel label1;
  private JLabel label2;
  private JLabel label3;
  JComboBox  cbox1;
  JComboBox cbox2;
  String [ ] roomChoice = {"1 Bedroom: $600","2 Bedroom: $800","3 Bedroom: $1000"};
 String [] activityChoice = {"Horse Back Riding: $60","Rafting: $40","Row Boat Rental:       $50"};
  ImageIcon icon1 = new ImageIcon("C:\\Users\\Coding\\Desktop\\cottage.jpeg");
  Font f1 = new Font("Ariel", Font.BOLD, 30);

//constructor 
  public CottageRental2(){
    super("Cottage Rental"); 
    con = getContentPane(); 
    con.setLayout(new BorderLayout()); 
    con.setBackground(Color.GRAY);
    setSize(WIDTH, HEIGHT);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
}

  public void createGUI(){
    label1 = new JLabel("Woodberry Cottage Rental", JLabel.CENTER);
    label1.setFont(f1);
    label1.setForeground(Color.WHITE);
    label2 = new JLabel("Rental Amount Due: ", JLabel.CENTER);
    label2.setFont(f1);
    label2.setForeground(Color.WHITE);
    label3 = new JLabel(icon1);
    cbox1 = new JComboBox();
    cbox1.addItem(roomChoice);
    cbox2 = new JComboBox();
    cbox2.addItem(activityChoice);
    con.add(label1, BorderLayout.NORTH);
    con.add(label2, BorderLayout.SOUTH);
    con.add(label3, BorderLayout.CENTER);
    con.add(cbox1, BorderLayout.WEST);
    con.add(cbox2, BorderLayout.EAST);
  }

  public void itemStateChanged(ItemEvent event){
    Object source = event.getSource();
    if(source == roomChoice){
      int roomIndex = roomChoice.getSelectedIndex();
      if(roomIndex == 1){
        int price1 = 600;
      }
      if(roomIndex == 2){
        int price1 = 800;
      }
      if(roomIndex == 3){
        int price1 = 1000;
      }
    }
    if(source == activityChoice){
      int activityIndex = activityChoice.getSelectedIndex();
      if(activityIndex == 1){
        int price2 = 60;
      }
      if(activityIndex == 2){
        int price2 = 40;
      }
      if(activityIndex == 3){
        int price2 = 50;
      }
    }
  }

  public static void main(String[] args){
    CottageRental2 object = new CottageRental2(); 
    object.createGUI();
    object.setSize(675, 320);
  }
}

1 个答案:

答案 0 :(得分:0)

您正在getSelectedIndex()String[])上调用roomChoice,但数组没有该名称的方法。所以,它告诉你它找不到那种方法。

我相信你的意思是cbox1.getSelectedIndex()。这同样适用于activityChoicecbox2