1.在做用Swing组件往数据库插入数据的实验时,我为JRadioButon添加了一个用内部类写的点击事件,用外部类的Radiotext成员获取JRadioButton的text内容并传入数据库,然而在反复调试的过程中Radiotext的值始终为初始值null,有朋友知道怎么解决吗?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class JudgeEdit extends BaseFrameEdit {
private JTextArea txtQuestion;
private JRadioButton rbtnT;
private JRadioButton rbtnF;
private String radioText = null;
private String txtQuestionText;
private radioAction RadioAction = new radioAction();
private PreparedStatement sql;
public JudgeEdit(){
super.setTitle("添加判断题");
}
protected void addControls() {
//题目
JLabel lblName = new JLabel("题目:");
lblName.setBounds(50, 10, 50, 25);
super.add(lblName);
txtQuestion = new JTextArea();
txtQuestion.setBounds(100, 10, 200, 270);
super.add(txtQuestion);
//答案
JLabel lblAnswer = new JLabel("答案:");
lblAnswer.setBounds(50, 285, 50, 25);
super.add(lblAnswer);
rbtnT = new JRadioButton("正确");
rbtnT.setBounds(100, 285, 100, 25);
rbtnT.addActionListener(RadioAction);
super.add(rbtnT);
rbtnF = new JRadioButton("错误");
rbtnF.setBounds(200, 285, 100, 25);
rbtnF.addActionListener(RadioAction);
super.add(rbtnF);
ButtonGroup btnGroup = new ButtonGroup();
btnGroup.add(rbtnT);
btnGroup.add(rbtnF);
//保存
JButton btnSave = new JButton("保存");
btnSave.setBounds(170, 320, 60, 25);
btnSave.addActionListener(new btnSaveAction());
super.add(btnSave);
}
class radioAction implements ActionListener{
public void actionPerformed(ActionEvent arg0){
if(rbtnT.isSelected()){
radioText = rbtnT.getText();
System.out.println(radioText);
}
if(rbtnF.isSelected()){
radioText = rbtnF.getText();
System.out.println(radioText);
}
}
}
class btnSaveAction implements ActionListener{
public void actionPerformed(ActionEvent e){
txtQuestionText = txtQuestion.getText();
Conn c = new Conn();
Connection con = c.getConnection();
try{
sql = con.prepareStatement("insert into JudgeList(JText,JAnswer)" + "values(?,?)");
sql.setString(1,txtQuestionText);
sql.setString(2,radioText);
sql.executeUpdate();
System.out.println("添加判断题成功!");
}
catch(Exception e2){
e2.printStackTrace();
}
}
}
}