I'm trying to get to grips with java swing and was testing out radio buttons. My code is:
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 get the following error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Scafhome.RunActionPerformed(Scafhome.java:50)
This is at: "if (bandButton.isSelected()) {"
I thought 'bandButton' had been created and marked as 'selected' - or have I misunderstood something?
Many thanks, Curly.