我正试图掌握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();
}
});
}
}
不幸的是我收到以下错误消息:
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at Scafhome.RunActionPerformed(Scafhome.java:50)
这是在:
“if(bandButton.isSelected()){”
我认为’bandButton’已被创建并标记为“已选中” – 或者我误解了某些内容?
非常感谢,
卷曲.
解决方法:
你正在影响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();
请注意,您正在为您在类中声明的所有三个变量执行此操作.