0

これは Swing に関する私の問題です:
1 つのテキストフィールドと 1 つのボタンを持つフレームを想像してください。このフレームの背後には、1 つのフィールドを持つデータ クラスがあります。

  • textfield には、FocusOut の textfield の値でデータ クラス フィールドを更新する FocusListener があります。
  • ボタンには、クリック時にデータクラスをサーバーに送信する ActionListener があります

テキストフィールドの値を変更してすぐにボタンをクリックすると、古い値のデータクラスがサーバーに送信されることがあります。ボタンの ActionPerformed イベントの前に textfield の FocusOut イベントが処理されるという保証はないように思えます。もしそうなら、それを確保する方法はありますか?私はいくつかのきれいな方法を意味します。必要でない場合は、それについてすべて汚したくありません。

4

4 に答える 4

2

楽しみのために、InputVerifier で実装された貧しい人の単方向バインディング: フォーカスを移す前に inputVerifier にアクセスすることが保証されていることに注意してください (そして、jdk の現在のバージョンで動作しているようです - 古いバージョンではいくつかの問題がありました)。ベリファイアで更新を行うことは、フォーカス転送がコミット アクションに関係している限り安全です。

ベリファイアといくつかの粗いデータ オブジェクト:

/**
 * Very simple uni-directional binding (component --> data) class.
 */
public static class BindingVerifier extends InputVerifier {

    private RawData data;
    private boolean first;
    public BindingVerifier(RawData data, boolean first) {
        this.data = data;
        this.first = first;
    }


    @Override
    public boolean shouldYieldFocus(JComponent input) {
        String text = ((JTextComponent) input).getText();
        if (first) {
            data.one = text;
        } else {
            data.two = text;
        }
        return true;
    }


    @Override
    public boolean verify(JComponent input) {
        return true;
    }

}

public static class RawData {
    String one;
    String two;
    public RawData(String one, String two) {
        this.one = one;
        this.two = two;
    }

    public String toString() {
        return one + "/" + two;
    }
}

使用法:

final RawData data = new RawData(null, null);
JTextField first = new JTextField(20);
first.setInputVerifier(new BindingVerifier(data, true));
JTextField second = new JTextField(20);
second.setInputVerifier(new BindingVerifier(data, false));
Action commit = new AbstractAction("commit") {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(data);
    }
};
JComponent form = new JPanel();
form.add(first);
form.add(second);
form.add(new JButton(commit));
于 2013-04-10T16:14:19.840 に答える
1

テキストフィールドの値を変更してすぐにボタンをクリックすると、古い値のデータクラスがサーバーに送信されることがあります。ボタンの ActionPerformed イベントの前に textfield の FocusOut イベントが処理されるという保証はないように思えます。もしそうなら、それを確保する方法はありますか?

フォームを別の方法で設計します。ボタンをクリックすると、ActionListener はフォーム上のすべてのテキスト フィールドで getText() メソッドを呼び出す必要があります。

于 2013-04-10T15:42:32.640 に答える
1

あなたはそのようにすることができます。私は疑似コードを与えているだけです。

private boolean check = false;

txtField FocusOutMethod {
 check = true;
}

button ActionPerformedMethod(){

 if(check){

      place your code that you want to execute in button click.

      check = false;
 }
}

これにより、actionPerformed メソッドは focusOut メソッドの実行後にのみコードを実行します。

于 2013-04-10T13:05:43.527 に答える