PassiveTextField1.java Source code

Java tutorial

Introduction

Here is the source code for PassiveTextField1.java

Source

/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.text.Keymap;

public class PassiveTextField1 extends JTextField {

    public static void main(String[] args) {
        JFrame f = new JFrame("Passive Text Field");
        f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
        final JTextField ptf = new JTextField(32);
        JTextField tf = new JTextField(32);
        JPanel p = new JPanel();
        JButton b = new JButton("OK");
        p.add(b);
        f.getContentPane().add(ptf);
        f.getContentPane().add(tf);
        f.getContentPane().add(p);

        Keymap map = ptf.getKeymap(); // Gets the shared map
        KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        map.removeKeyStrokeBinding(key);

        ActionListener l = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                System.out.println("Action event from a text field");
            }
        };
        ptf.addActionListener(l);
        tf.addActionListener(l);

        // Make the button the default button
        f.getRootPane().setDefaultButton(b);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                System.out.println("Content of text field: <" + ptf.getText() + ">");
            }
        });
        f.pack();
        f.setVisible(true);
    }
}