AddingActionCommandActionListenerSample.java Source code

Java tutorial

Introduction

Here is the source code for AddingActionCommandActionListenerSample.java

Source

import java.awt.BorderLayout;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

public class AddingActionCommandActionListenerSample {
    public static void main(String args[]) {
        final JFrame frame = new JFrame("Default Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField textField = new JTextField();
        frame.add(textField, BorderLayout.NORTH);
        frame.add(new JTextField(), BorderLayout.SOUTH);

        InputVerifier verifier = new InputVerifier() {
            public boolean verify(JComponent input) {
                final JTextComponent source = (JTextComponent) input;
                String text = source.getText();
                if ((text.length() != 0) && !(text.equals("Exit"))) {
                    JOptionPane.showMessageDialog(frame, "Can't leave.", "Error Dialog", JOptionPane.ERROR_MESSAGE);
                    return false;
                } else {
                    return true;
                }
            }
        };
        textField.setInputVerifier(verifier);

        frame.setSize(250, 150);
        frame.setVisible(true);
    }
}