我有一个项目,必须通过setEnabled()启用和禁用按钮(addRn,addSw和addCy)的使用。我已经尝试了很多事情,包括添加documentListener,但我感到困惑。有谁知道该怎么办?
ArrayList<JTextField> run = new ArrayList<>();
run.add(intervals);
run.add(minRest);
ArrayList<JTextField> swim = new ArrayList<>();
swim.add(intervals);
swim.add(minRest);
swim.add(loc);
ArrayList<JTextField> cycle = new ArrayList<>();
cycle.add(tempo);
cycle.add(terrain);
DocumentListener listener = new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
boolean canEnable = true;
for (JTextField intervals : run) {
intervals.getDocument().addDocumentListener(listener);
if (intervals.getText().isEmpty()) {
canEnable = false;
}
}
for (JTextField minRest : run) {
if (minRest.getText().isEmpty()) {
canEnable = false;
}
}
addRn.setEnabled(canEnable);
}
};
这是我到目前为止所拥有的,但是我感觉好像有很多失踪之处,而且我对发现问题的认识还不够。我尝试按照建议的方法进行处理here
UPDATE我设法弄清楚了
public class TrainingRecordGUI extends JFrame implements ActionListener, DocumentListener {
将DocumentListener添加到公共类中
然后使用您要使用的文本字段注册DocumentListener
public TrainingRecordGUI() {
add(intervals);
intervals.setEditable(true);
intervals.getDocument().addDocumentListener(this); //addDocumentListener for button enabling
add(labminr);
add(minRest);
minRest.setEditable(true);
minRest.getDocument().addDocumentListener(this);//addDocumentListener for button enabling
add(labloc);
add(loc);
loc.setEditable(true);
loc.getDocument().addDocumentListener(this);//addDocumentListener for button enabling
add(labter);
add(terrain);
terrain.setEditable(true);
terrain.getDocument().addDocumentListener(this);//addDocumentListener for button enabling
add(labtempo);
add(tempo);
tempo.setEditable(true);
tempo.getDocument().addDocumentListener(this);//addDocumentListener for button enabling
}
然后为应该启用和不应该启用按钮的情况添加最终代码
// Button enabling/disabling code
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
//boolean variables to set run, swim and cycle button enabled
boolean canEnableRn = false;
boolean canEnableSw = false;
boolean canEnableCy = false;
//if anything but necessary fields for run filled
if (intervals.getText().equals("") && minRest.getText().equals("")
|| !intervals.getText().equals("") && minRest.getText().equals("")
|| intervals.getText().equals("") && !minRest.getText().equals("")
|| !loc.getText().equals("") && !terrain.getText().contentEquals("") && !tempo.getText().equals("")) {
canEnableRn = false; // set canEnableRn false to prevent the button to be enabled
}else { canEnableRn = true;} //else set true and allow user to add to run
addRn.setEnabled(canEnableRn); // set button to boolean value
}