如何在Netbeans上为Java桌面应用程序设置单选按钮的初始值?

时间:2013-04-11 14:47:46

标签: java swing netbeans jradiobutton

我正在使用的这个应用程序有三个单选按钮,但我需要打开JFrame,其中一个选中,另外两个没有。

加载JFrame后,我调用以下方法:

private void initJRadio() {
    jRadioButton1.setSelected(false);
    jRadioButton2.setSelected(true);
    jRadioButton3.setSelected(false);
}

但是在加载JFrame时我得到以下异常:

  

线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException       在StockJFrame.initJRadio(StockJFrame.java:139)

StockJFrame是类名,139是“jRadioButton1.setSelected(false);”的行号。

在此类的“源”窗格中,Netbeans添加了以下行:

jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();

jRadioButton1.setText(/*label value*/);
jRadioButton1.setToolTipText(/*some tooltip text*/);
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jRadioButton1ActionPerformed(evt);
    }
});

jRadioButton2.setText(/*label value*/);
jRadioButton2.setToolTipText(/*some tooltiptext*/);
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jRadioButton2ActionPerformed(evt);
    }
});

jRadioButton3.setText(/*label value*/);
jRadioButton3.setToolTipText(/*some tooltip text*/);
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jRadioButton3ActionPerformed(evt);
    }
});

如何正确设置?

1 个答案:

答案 0 :(得分:1)

在您的代码中的某个时刻,jRadioButton1(和其他人)必须(可能已经是)通过jRadioButton1 = new javax.swing.JRadioButton()进行初始化。

如果我没有弄错,NetBeans生成的代码默认情况下会在名为initComponents()的方法中进行初始化。此外,initComponents()通常在构造函数中调用。

找出正在进行初始化的位置(initComponents()或其他地方)并确保initJRadio()仅在之后被称为

<强>更新

发布更多代码后,您可以在粘贴的最后一个命令后立即调用initJRadio()。 (即jRadioButton3.addActionListener(new ... });)。

PS:java.lang.NullPointerException表示您的对象尚未null,也就是说,如上所述,它尚未初始化。