Java swing radio buttons - java.lang.NullPointerException
I am trying to deal with java swing and have tested switches. My code:
import java.awt.*;
import javax.swing.*;
import javax.swing.ButtonGroup;
public class Scafhome extends javax.swing.JFrame {
private JRadioButton bandButton;
private JRadioButton gelButton;
private JButton jbtnRun;
public Scafhome() {
JFrame jfrm = new JFrame("Scaffold search ...");
jfrm.setLayout (new GridLayout(8,2));
jfrm.setSize(320,220);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton bandButton = new JRadioButton();
bandButton.setText("Band-id");
bandButton.setSelected(true);
JRadioButton gelButton = new JRadioButton();
gelButton.setText("Gelc-ms");
ButtonGroup group = new ButtonGroup();
group.add(bandButton);
group.add(gelButton);
JButton jbtnRun = new JButton("RUN");
jbtnRun.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunActionPerformed(evt);
}
});
jfrm.add(bandButton);
jfrm.add(gelButton);
jfrm.add(jbtnRun);
jfrm.setVisible(true);
}
private void RunActionPerformed(java.awt.event.ActionEvent evt) {
String radioText="";
if (bandButton.isSelected()) {
radioText=bandButton.getText();
}
if (gelButton.isSelected()) {
radioText=gelButton.getText();
}
javax.swing.JOptionPane.showMessageDialog( Scafhome.this, radioText );
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Scafhome();
}
});
}
}
Unfortunately I am getting the following error:
Exception on stream "AWT-EventQueue-0" java.lang.NullPointerException in Scafhome.RunActionPerformed (Scafhome.java:50)
This is: "if (bandButton.isSelected ()) {"
I thought the "bandButton" was created and marked as "selected" - or am I missing something?
Thank you very much Curly.
+3
source to share
1 answer
You shadow the bandButton variable - you re-declare it in the constructor and you initialize the local variable but not the class field leaving the class field null. Solution - don't re-declare the variable.
To be explicit, change this:
public class Scafhome extends javax.swing.JFrame {
private JRadioButton bandButton;
//...
public Scafhome() {
//...
// re-declared variable!
JRadioButton bandButton = new JRadioButton();
:
public class Scafhome extends javax.swing.JFrame {
private JRadioButton bandButton;
//...
public Scafhome() {
//...
// variable not re-declared
bandButton = new JRadioButton();
Note that you are doing this for all three variables that you declared in the class.
+8
source to share