在JWindow中添加可变长度的JRadioButtons数组



大家好,我试图添加一个可变长度的数组到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)

检查分配前是否创建了jRadioButton数组

你需要初始化你的JRadioButton数组

JRadioButton jRadioButton[] = new JRadioButton[someValue];

您可能希望初始化数组的第i个字段,而不是总是初始化最后一个字段:

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

代替:

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

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

相关内容

  • 没有找到相关文章

最新更新