временно отключить кнопку ОК на JDialog, в соответствии с проверкой JTextField - PullRequest
2 голосов
/ 12 октября 2011

У меня есть JDialog, созданный подобным образом , в соответствии с учебником Oracle .

с помощью конструктора JOptionPane:

optionPane = new JOptionPane(array,
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION,
                null,
                options,
                options[0]);

У меня нет ссылок на кнопки "да" и "нет", потому что они создаются конструктором JOptionPane.

Теперь в моем диалоге у меня есть поле JFormattedText с созданным мной InputValidator, которое непрерывно проверяет ввод текстового поля:

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);

1 Ответ

3 голосов
/ 16 октября 2011

Вы можете попробовать что-то вроде этого, чтобы найти кнопки в диалоге JOptionPane.

public class Snippet {

    public static void main(String[] args) {
        JOptionPane optionPane = new JOptionPane("Test",
                        JOptionPane.QUESTION_MESSAGE,
                        JOptionPane.YES_NO_OPTION,
                        null);

        List<JButton> buttons = new ArrayList<JButton>();

        loadButtons(optionPane, buttons);

    }

    public static void loadButtons(JComponent  comp, List<JButton> buttons) {
        if (comp == null) {
            return;     
        }

        for (Component c : comp.getComponents()) {
            if (c instanceof JButton) {
                buttons.add((JButton) c);

            } else if (c instanceof JComponent) {
                loadButtons((JComponent) c, buttons);
            }
        }
    }

}
...