モジュール java.desktop
パッケージ javax.swing

クラスInputVerifier

java.lang.Object
javax.swing.InputVerifier

public abstract class InputVerifier extends Object
このクラスは、Swingコンポーネントの検証メカニズムを提供します。 GUIでは、ユーザーが入力フォーカスをナビゲートできるようにする前に、コンポーネントが有効な状態であることを確認する必要があります。 これを行うには、クライアントはInputVerifierのサブクラスを作成し、JComponentsetInputVerifierメソッドを使用して、そのサブクラスのインスタンスをフォーカス転送操作のソースであるJComponentにアタッチします。 InputVerifierでは、フォーカスが拒否される可能性があるフォーカス転送のターゲットに対して検証することもできます。 ソースSwingコンポーネントからターゲットSwingコンポーネントにフォーカスが転送される前に、入力ベリファイアのshouldYieldFocus(source, target)メソッドがコールされます。 そのメソッドがtrueを返した場合にのみフォーカスが転送されます。

次の例では2つのテキスト・フィールドがあり、最初のフィールドでは、ユーザーから文字列「pass」が入力されるのを待っています。 最初のテキスト・フィールドにその文字列が入力されているか、2番目のテキスト・フィールドに"accept"文字列が含まれている場合、ユーザーはその文字列内をクリックするか、TABを押して2番目のテキスト・フィールドにフォーカスを進めることができます。 ただし、最初のテキスト・フィールドに別の文字列が入力され、2番目のテキスト・フィールドに"accept"が含まれない場合、ユーザーはフォーカスを2番目のテキスト・フィールドに転送できません。

 import java.awt.*;
 import javax.swing.*;

 // This program demonstrates the use of the Swing InputVerifier class.
 // It creates two text fields; the first of the text fields expects the
 // string "pass" as input, and will allow focus to advance to the second text
 // field if either that string is typed in by the user or the second
 // field contains "accept" string.

 public class VerifierTest extends JFrame {

     public VerifierTest() {
         JTextField field1 = new JTextField("Type \"pass\" here");
         JTextField field2 = new JTextField("or \"accept\" here");
         getContentPane().add(field1, BorderLayout.NORTH);
         getContentPane().add(field2, BorderLayout.SOUTH);

         field1.setInputVerifier(new InputVerifier() {
             public boolean verify(JComponent input) {
                return "pass".equals(((JTextField) input).getText());
             }

             public boolean verifyTarget(JComponent input) {
                 return "accept".equals(((JTextField) input).getText());
             }

             public boolean shouldYieldFocus(JComponent source,
                                                          JComponent target) {
                 return verify(source) || verifyTarget(target);
             }
         });

         pack();
         setVisible(true);
     }

     public static void main(String[] args) {
         SwingUtilities.invokeLater(VerifierTest::new);
     }
 }
 

導入されたバージョン:
1.3