java swing单选按钮 - java.lang.NullPointerException

时间:2014-09-18 11:02:27

标签: java swing nullpointerexception jradiobutton

我正试图掌握java swing并且正在测试单选按钮。我的代码是:

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

}

不幸的是我收到以下错误消息:

  

线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException     在Scafhome.RunActionPerformed(Scafhome.java:50)

这是: “if(bandButton.isSelected()){”

我认为'bandButton'已被创建并标记为“已选中” - 或者我误解了某些内容?

非常感谢, 卷曲。

1 个答案:

答案 0 :(得分:8)

你正在对bandButton变量进行遮蔽 - 你在构造函数中重新声明它并初始化本地重新声明的变量,而不是类字段,而是将类字段保留为null。解决方案 - 不要重新声明变量。

明确地说,改变一下:

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

请注意,您正在为在类中声明的所有三个变量执行此操作。