使用多维表中的项填充JComboBox

时间:2013-04-24 00:18:22

标签: java swing netbeans nullpointerexception jcombobox

我正在尝试从多维表格中的项目填充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”中的异常java.lang.NullPointerException     在temps.interfac $ 2.run(interfac.java:125)at   java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)at   java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)at 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)     在java.awt.EventQueue.dispatchEvent(EventQueue.java:697)at   java.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)     at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

2 个答案:

答案 0 :(得分:2)

您的错误告诉您jComboBox1变量为null。

解决方案:在使用之前先初始化变量。


编辑:
你说:

  

变量已经初始化,因为我使用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告诉你的内容。

答案 1 :(得分:2)

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

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

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

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

另见Arrays