我目前正在做一个涉及文本字段和复选框的表单。我已经将复选框链接到文本字段,如果复选框是SELECTED,则启用文本字段;如果复选框已取消,则禁用文本字段。
我现在的问题是,如果用户选中复选框并在文本字段中键入一些值,然后再次取消选中该复选框,我的程序仍将从禁用的文本字段中读取输入。有没有办法克服这个问题?以下是我的编码:
private void pnl1submitbtnActionPerformed(java.awt.event.ActionEvent evt) {
moduleFunc moduleFunc;
String module = moduletxtfield.getText();
double exam = Double.parseDouble(examtextfield.getText());
double ct = Double.parseDouble(cttextfield.getText());
double quiz = Double.parseDouble(quiztextfield.getText());
double assign = Double.parseDouble(asstextfield.getText());
try {
if (module.trim().isEmpty()) {
moduleerrorlbl.setText("Field cannot be empty");
}
else if (!(exam+ct+quiz+assign == 100)) {
markerrorlbl.setText("Total marks must be 100");
}
else
{
markerrorlbl.setText("");
moduleerrorlbl.setText("");
}
感谢。
编辑:
谢谢你们,我已经弄清楚它是如何运作的。
private void pnl1submitbtnActionPerformed(java.awt.event.ActionEvent evt) {
moduleFunc moduleFunc;
String module = moduletxtfield.getText();
double exam = 0.0, assign = 0.0, quiz = 0.0, ct = 0.0;
try {
if (module.trim().isEmpty()) {
moduleerrorlbl.setText("Field cannot be empty");
}
else if (OODJ.moduleRecord.containsKey(module)) {
moduleerrorlbl.setText("Module already exists!");
}
else {
if (examchkbox.isSelected()) {
exam = Double.parseDouble(examtextfield.getText());
}
if(ctchkbox.isSelected()) {
ct = Double.parseDouble(cttextfield.getText());
}
if(quizchkbox.isSelected()) {
quiz = Double.parseDouble(quiztextfield.getText());
}
if(asschkbox.isSelected()) {
assign = Double.parseDouble(asstextfield.getText());
}
if (!(exam + ct + quiz + assign == 100)) {
markerrorlbl.setText("Total marks must be 100");
}
else {
// self-coded
}
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
答案 0 :(得分:1)
您必须在选择与JCheckBox
关联的JTextField
时进行检查。为此,您必须使用isSelected()
的{{1}}方法。
示例:
JCheckBox
答案 1 :(得分:0)
如果您不希望在禁用TF时读取TF,则可以轻松检查它。
编辑:立即使用您的示例:
private void pnl1submitbtnActionPerformed(java.awt.event.ActionEvent evt {
moduleFunc moduleFunc;
String module = moduletxtfield.getText();
double exam = 0, ct = 0, quiz = 0, assign = 0;
if(examtextfield.isEnabled())
exam = Double.parseDouble(examtextfield.getText());
if(cttextfield.isEnabled())
ct = Double.parseDouble(cttextfield.getText());
if(quiztextfield.isEnabled())
quiz = Double.parseDouble(quiztextfield.getText());
if(asstextfield.isEnabled())
assign = Double.parseDouble(asstextfield.getText());
try {
if (module.trim().isEmpty()) {
moduleerrorlbl.setText("Field cannot be empty");
}
else if (!(exam+ct+quiz+assign == 100)) {
markerrorlbl.setText("Total marks must be 100");
}
else
{
markerrorlbl.setText("");
moduleerrorlbl.setText("");
}
}
//do whatever you want with your double values.
}