/* (@)FormattedTextFieldTestGui.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 java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
/**
* Sample code for formatted text fields with separate display and edit
* formatters.
*
* @version $Revision$ as of $Date$
* @author Sebastian Haufe
* @since Playground-3.8
*/
public class FormattedTextFieldTestGui {
/** Creates the GUI. Call on EDT, only! */
static void createAndShowGui() {
/* create custom number formats */
final DecimalFormat displayFmt = new DecimalFormat("#.00");
final DecimalFormat editFmt = new DecimalFormat("#.##");
/* create custom formatters */
final NumberFormatter editFormatter = new NumberFormatter(editFmt);
final NumberFormatter displayFormatter = new NumberFormatter(displayFmt);
/* create formatted text field with my formatters */
final JFormattedTextField ftf = new JFormattedTextField();
ftf.setFormatterFactory(new DefaultFormatterFactory(displayFormatter,
displayFormatter, editFormatter));
/* select all on focus gained */
ftf.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
((JFormattedTextField) e.getComponent()).selectAll();
}
});
}
});
/* create and show test frame */
final JPanel contentPane = new JPanel(new BorderLayout(6, 6));
contentPane.add(ftf);
contentPane.add(new JButton("Dummy"), BorderLayout.SOUTH);
final JFrame f = new JFrame("Test Frame: FormattedTextFieldTestGui");
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();
}
});
}
}