3

我正在尝试将列表转换为数组,但出现错误,我不知道为什么。我正在使用当前时间并在 for 循环中获取今天剩余的时间并将其放入列表中。当我尝试将其更改为数组时出现错误。我尝试这样做是因为后来我在JCombobox

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.GregorianCalendar;
import java.util.Calendar;

public class Frame extends JFrame implements ActionListener{
    //JFrame elements
    private JButton btnSetTime;
    private JLabel lblTitle;
    private JComboBox comboTime;

    //Standard elements
    private Timer tillPopup, tillShutdown;

    Calendar calendar = new GregorianCalendar();
    int hour = (calendar.get(Calendar.HOUR_OF_DAY));
    List times = createDropdown(hour);
    // Convert ArrayList to array which can be used in the combobox
    String[] dropdownElements = times.toArray();

    String[] a = {"a","b"};
    public Frame(){
        setLayout(new FlowLayout());

        //Labels
        lblTitle = new JLabel("Deze applicatie sluit u computer automatisch af om het energieverbruik te verminderen.");

        //Combobox
        comboTime = new JComboBox(a);
        comboTime.setSelectedIndex(0);

        //Button
        btnSetTime = new JButton("Zet afsluittijd");

        //Timers
        //tillPopup = new Timer(this);
        //tillShutdown = new Timer(this);

        //Add elements to Frame
        add(lblTitle);
        add(comboTime);
        add(btnSetTime);

        //Add actionListeners
        btnSetTime.addActionListener(this);

        setSize(500,300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    private List createDropdown(int hour){
        List availableHours = new List();
        for(int i = hour; i <=24; i++){
            if (i != 24){
                availableHours.add(i + ":00");
            }
            else if(i == 24){
                availableHours.add("00:00");
            }
        }
        return availableHours;
    }
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == btnSetTime){
            Object popupTime = comboTime.getSelectedItem();
                System.out.println(popupTime);

        }
    }
}

我收到以下错误:

Frame.java:21: error: cannot find symbol  
String[] dropdownElements = times.toArray();  
                                 ^  
    symbol:   method toArray()  
    location: variable times of type List

如何将我从数组返回的列表更改为method createDropdown数组,为什么我做错了什么?

4

1 回答 1

5

既然你已经导入import java.awt.*;了,List使用的是java.awt.List. 您需要添加一个导入 - java.util.List

请不要使用原始类型List。不建议在较新的代码中使用原始类型。当然你不可能注意到它,因为它java.awt.List是一个非泛型类。所以即使是编译器也不会给你警告信息。

您应该使用参数化类型 -List<String>在您的情况下。将您的方法修改为:

private List<String> createDropdown(int hour){
    List<String> availableHours = new ArrayList<String>();
    ...
}

您还需要添加import java.util.ArrayList.

于 2013-10-07T17:55:54.483 回答