how to set radio buttons initial value on Netbeans for a Java desktop application?

gtludwig picture gtludwig · Apr 11, 2013 · Viewed 18.4k times · Source

This app I'm working on has three radio buttons, but I need to open the JFrame with one of them selected and the other two not.

Upon the JFrame load, I call the following method:

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

But I get the following exception upon loading the JFrame:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at StockJFrame.initJRadio(StockJFrame.java:139)

Where StockJFrame is the class name and 139 is the line number for "jRadioButton1.setSelected(false);"

On the Source pane for this class, Netbeans has added these lines:

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);
    }
});

How to correctly set this up?

Answer

acdcjunior picture acdcjunior · Apr 11, 2013

At some point in your code, the jRadioButton1 (and others) must be (they probably already are) initialized through a jRadioButton1 = new javax.swing.JRadioButton().

If I'm not mistaken, NetBeans generated code, by default, does that initialization in a method called initComponents(). Also, initComponents() is usually called at the constructor.

Find out where the initialization is taking place (initComponents() or elsewhere) and make sure initJRadio() is only called after that.

Update:

After you posted more of your code, you can put the initJRadio() call right after the last command you pasted. (Namely, jRadioButton3.addActionListener(new ... });).

PS.: The java.lang.NullPointerException means that your object is yet null, that is, as pointed above, it has not yet been initialized.