将具有可变长度的JRadioButton数组添加到JWindow

时间:2013-03-21 09:56:19

标签: java arrays swing jradiobutton jwindow

大家好我试图向JWindow添加一个可变长度数组,但是我遇到了运行时错误。想从这里得到帮助..

这是我的代码:

    package components;

import java.util.Calendar;

public class FullDay extends javax.swing.JWindow {

    public FullDay() {
        initComponents();
    }                         
    private void initComponents() {

        int i;
//to get the no of days of the current month.

        Calendar cal = Calendar.getInstance();
        int maxdays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        getContentPane().setLayout(new java.awt.FlowLayout());

//Creating an array of radiobuttons having size equal to the no of days of the current //month

        for(i=0; i<maxdays; i++) {
            jRadioButton[maxdays] = new javax.swing.JRadioButton();
            getContentPane().add(jRadioButton[i]);
        }        

        pack();

    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FullDay().setVisible(true);
            }
        });
    }
    private javax.swing.JRadioButton jRadioButton[];
}

但我得到的错误是:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at components.FullDay.initComponents(FullDay.java:18)
at components.FullDay.<init>(FullDay.java:8)
at components.FullDay$1.run(FullDay.java:30)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

3 个答案:

答案 0 :(得分:1)

在分配之前检查jRadioButton数组是否已创建。

答案 1 :(得分:1)

你需要初始化你的JRadioButton数组

JRadioButton jRadioButton[] = new JRadioButton[someValue];

答案 2 :(得分:0)

您可能想要初始化数组的第i个字段,而不是始终初始化最后一个字段:

 jRadioButton[i] = new javax.swing.JRadioButton();

而不是:

 jRadioButton[maxdays] = new javax.swing.JRadioButton();

此外,正如之前的答案所述,在循环之外创建数组本身。