3
我想将列表转换为数组,但我得到一个错误,我找不出原因。我正在采取当前的时间,并且在for循环中,我将今天的其余时间放到列表中。当我尝试将其更改为数组时,出现错误。我尝试,因为后来我用的是阵列中的JCombobox
方法toArray()不工作在列表
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
更改到一个数组和为什么我做错了?
您的解决方案效果很好,但我不明白为什么我必须在其后面放置''。 util和awt'list'有什么区别。 PS。我是一个初学者 –
@GertKommer''代表一个实际的类型参数。你需要把它放在因为java.util.List是泛型类型。你可以从http://docs.oracle.com/javase/tutorial/java/generics/ –
@GertKommer了解更多关于泛型的知识或者对于快速的基本介绍,我写了一篇博文 - http://rjcodeblog.wordpress .com/2013/09/28/java-generics-a-basic-introduction /。这会给你一个快速的开始。 –