根据 Oracle 的教程,我以这样的方式创建了一个 JDialog 。
使用 JOptionPane 构造函数:
optionPane = new JOptionPane(array,
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]);
我没有提到“是”和“否”按钮,因为它们是由 JOptionPane 构造函数创建的。
现在,在我的对话框中,我有一个带有我创建的 InputValidator 的 JFormattedText 字段,它不断验证文本字段的输入:
public class ValidatedDoubleField extends InputVerifier implements DocumentListener {
private JTextField field;
private Border defaultBorder;
public ValidatedDoubleField(JFormattedTextField f){
this.field = f;
this.defaultBorder = f.getBorder();
f.getDocument().addDocumentListener(this);
}
@Override
public boolean verify(JComponent input) {
//System.out.println("verify");
if (input instanceof JTextField){
JTextField f = (JTextField)input;
try{
Double value = Double.parseDouble(f.getText().replace(',', '.'));
return true;
}catch (NumberFormatException e){
return false;
}
}else if (input instanceof JFormattedTextField){
JFormattedTextField f = (JFormattedTextField)input;
try{
Double value = Double.parseDouble(f.getText().replace(',', '.'));
return true;
}catch (NumberFormatException e){
return false;
}
}
return false;
}
public boolean shouldYieldFocus(JComponent input){
boolean inputOK = verify(input);
if (inputOK) {
if (input instanceof JTextField){
JTextField f = (JTextField)input;
f.setBorder(defaultBorder);
return true;
}else if (input instanceof JFormattedTextField){
JFormattedTextField f = (JFormattedTextField)input;
f.setBorder(defaultBorder);
return true;
}else
return false;
} else {
if (input instanceof JTextField){
JTextField f = (JTextField)input;
f.setBorder(BorderFactory.createLineBorder(Color.red));
Toolkit.getDefaultToolkit().beep();
return false;
}else if (input instanceof JFormattedTextField){
JFormattedTextField f = (JFormattedTextField)input;
f.setBorder(BorderFactory.createLineBorder(Color.red));
Toolkit.getDefaultToolkit().beep();
return false;
}else
return false;
}
//return true;
}
@Override
public void changedUpdate(DocumentEvent e) {
this.field.getInputVerifier().shouldYieldFocus(field);
}
@Override
public void insertUpdate(DocumentEvent e) {
this.field.getInputVerifier().shouldYieldFocus(field);
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
this.field.getInputVerifier().shouldYieldFocus(field);
}
}
我发布了 InputVerifier 代码,即使它与问题不太相关。
现在我想做的是暂时禁用“确定”按钮,直到该字段得到验证,但我没有引用它。
我怎样才能做到这一点?
我正在寻找类似的东西:
JButton b = optionPane.getOkButton();
if (myFieldNotValidate)
b.setEnabled(false);