/* (@)NumberTextFieldTestGui.java */
/* Copyright 2010 Sebastian Haufe
* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[url]http://www.apache.org/licenses/LICENSE-2.0[/url]
* Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.ebenius;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.*;
/**
* @author Sebastian Haufe
*/
public class NumberTextFieldTestGui {
/** Creates the GUI. Call on EDT, only! */
static void createAndShowGui() {
final PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(
FilterBypass fb,
int offset,
String string,
AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, filterInputString(string), attr);
}
@Override
public void replace(
FilterBypass fb,
int offset,
int length,
String string,
AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, filterInputString(string), attrs);
}
private String filterInputString(String string) {
StringBuilder sb = null;
for (int i = 0; i < string.length(); i++) {
final char input = string.charAt(i);
final char accepted = toAcceptedCharacter(input);
if (input != accepted && sb == null) {
sb = new StringBuilder(string.length());
if (i > 0) {
sb.append(string, 0, i - 1);
}
}
if (sb != null && accepted != '\u0000') {
sb.append(accepted);
}
}
return sb == null ? string : sb.toString();
}
private char toAcceptedCharacter(char c) {
return Character.isLowerCase(c)
? Character.toUpperCase(c)
: Character.isUpperCase(c) ? c : '\u0000';
}
});
final JPanel contentPane = new JPanel(new BorderLayout(6, 6));
contentPane.add(new JTextField(doc, "0", 12));
final JFrame f = new JFrame("Test Frame: NumberTextFieldTestGui"); //$NON-NLS-1$
f.setContentPane(contentPane);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
/** @param args ignored */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}