1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License, Version 1.0 only 6 * (the "License"). You may not use this file except in compliance 7 * with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or http://www.opensolaris.org/os/licensing. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* 23 * ident "%Z%%M% %I% %E% SMI" 24 * 25 * Copyright (c) 1998-1999 by Sun Microsystems, Inc. 26 * All rights reserved. 27 */ 28 package com.sun.dhcpmgr.ui; 29 30 import java.awt.*; 31 import java.awt.event.*; 32 import javax.swing.*; 33 import javax.swing.text.*; 34 35 /** 36 * A text field which disallows whitespace in its input 37 */ 38 public class NoSpaceField extends JTextField { 39 40 /** 41 * Constructs an empty field, 20 characters wide. 42 */ 43 public NoSpaceField() { 44 this(""); 45 } 46 47 /** 48 * Constructs a field initialized to the provided text. Defaults to 49 * 20 characters wide. 50 * @param text the text to display initially 51 */ 52 public NoSpaceField(String text) { 53 this(text, 20); 54 } 55 56 /** 57 * Constructs a field initialized to the provided text with the requested 58 * size. 59 * @param text the text to display initially 60 * @param length the length in characters the field should size itself to 61 */ 62 public NoSpaceField(String text, int length) { 63 super(text, length); 64 } 65 66 protected Document createDefaultModel() { 67 return new NoSpaceDocument(); 68 } 69 70 /* 71 * This is the recommended way to validate input, as opposed to trapping 72 * KeyEvents because this will actually catch paste operations as well. 73 */ 74 static class NoSpaceDocument extends PlainDocument { 75 public void insertString(int offs, String str, AttributeSet a) 76 throws BadLocationException { 77 if (str != null) { 78 char [] chars = str.toCharArray(); 79 for (int i = 0; i < chars.length; ++i) { 80 if (Character.isWhitespace(chars[i])) { 81 throw new BadLocationException("", offs); 82 } 83 } 84 } 85 super.insertString(offs, str, a); 86 } 87 } 88 }