我正在尝试从多维表中的项目填充JCombobox。我要添加的项是该表中的城市名称。这是我的代码:
String t21[][] = {{"Azores","Alaska","Pacific Time US & Canada","Chihuahua, La Paz, Mazatlan - New","Guadalajara, Mexico City, Monterrey - New","Bogota, Lima, Quito, Rio Branco","Atlantic Time","CasaBlanca GMT","Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna","Athens, Bucharest, Istanbul","Moscow, St. Petersburg, Volgograd","Abu Dhabi, Muscat","Chennai, Kolkata, Mumbai, New Delh","Almaty, Novosibirsk","Bangkok, Hanoi, Jakarta","Beijing, Chongqing, Hong Kong, Urumqi","Osaka, Sapporo, Tokyo","Canberra, Melbourne, Sydney","",""},
{"-6","-5","-4","-3","-2","-1","0","1","2","3","4","5","6","7","8","9","10"}};
for( int i = 0; i< t21.length-1; i++){
jComboBox1.addItem(t21[0][i]);
}
但是当我运行程序时,我得到这个错误:
线程"AWT-EventQueue-0"异常. interface $2.run(interface .java:125java.awt.event.InvocationEvent.dispatch (InvocationEvent.java: 251)java.awt.EventQueue.dispatchEventImpl (EventQueue.java: 727)java.awt.EventQueue.access (EventQueue.java: 103) 200美元java.awt.EventQueue 3.美元(EventQueue.java: 688)运行java.awt.EventQueue 3.美元(EventQueue.java: 686)运行java.security.AccessController。特权(本地方法)在java.security.ProtectionDomain dointersectionprivilege 1.美元(ProtectionDomain.java: 76)在java.awt.EventQueue.dispatchEvent(EventQueue.java:697java.awt.EventDispatchThread.pumpOneEventForFilters (EventDispatchThread.java: 242)在java.awt.EventDispatchThread.pumpEventsForFilter (EventDispatchThread.java: 161)在java.awt.EventDispatchThread.pumpEventsForHierarchy (EventDispatchThread.java: 150)在java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java: 146)在java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java: 138)java.awt.EventDispatchThread.run (EventDispatchThread.java: 91)
您的错误告诉您jComboBox1变量为空。
解决方法:在使用变量之前先初始化它。
编辑:
你状态:
不要相信我的话,也不要相信你的假设。使用您的程序来测试这一点,看看代码中此时真正发生了什么。将代码修改如下:变量已经初始化,因为我在设计端使用NetBeans
创建了一个JComboBox
System.out.println("is jComboBox1 null: " + (jComboBox1 == null)); // *** added *
for( int i = 0; i< t21.length-1; i++){
jComboBox1.addItem(t21[0][i]);
}
然后请向我们报告JVM告诉您什么。
一旦jComboBox1
初始化,正如@气垫船充满鳗鱼的建议,一个新的问题浮出水面:只有一个单一的条目出现在组合中。检查循环限制的值,看看为什么:
System.out.println(t21.length-1);
假设您希望组合显示第一个行的元素,那么for-each循环可能更可靠:
for (String s : t21[0]) {
jComboBox1.addItem(s);
}
参见数组。