0

我正在尝试从多维表中的项目填充 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]);
               }

但是当我运行我的程序时,我得到了这个错误:

java.awt 的 java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 的 temps.interfac$2.run(interfac.java:125) 的线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常.EventQueue.dispatchEventImpl(EventQueue.java:727) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3 .run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java: 697) 在 java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 在 java.awt 的 java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)。EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread .java:91)

4

2 回答 2

2

jComboBox1正如@Hovercraft Full Of Eels 所建议的那样,一旦初始化,就会出现一个新问题:组合中只出现一个条目。检查循环限制的值以了解原因:

System.out.println(t21.length-1);

假设您希望组合显示第一的元素,则for-each循环可能更可靠:

for (String s : t21[0]) {
     jComboBox1.addItem(s);
}

另请参见数组

于 2013-04-24T03:01:55.987 回答
2

您的错误告诉您 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 告诉你什么。

于 2013-04-24T00:25:28.647 回答