下面列出了怎么用javax.swing.JFormattedTextField的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns either the default formatter, display formatter, editor
* formatter or null formatter based on the state of the
* JFormattedTextField.
*
* @param source JFormattedTextField requesting
* JFormattedTextField.AbstractFormatter
* @return JFormattedTextField.AbstractFormatter to handle
* formatting duties.
*/
public JFormattedTextField.AbstractFormatter getFormatter(
JFormattedTextField source) {
JFormattedTextField.AbstractFormatter format = null;
if (source == null) {
return null;
}
Object value = source.getValue();
if (value == null) {
format = getNullFormatter();
}
if (format == null) {
if (source.hasFocus()) {
format = getEditFormatter();
}
else {
format = getDisplayFormatter();
}
if (format == null) {
format = getDefaultFormatter();
}
}
return format;
}
@Override
public boolean stopCellEditing()
{
JFormattedTextField textField = (JFormattedTextField) getComponent();
if (textField.isEditValid())
{
try
{
textField.commitEdit();
}
catch (java.text.ParseException exc)
{
}
}
else
{ //text is invalid
if (!userSaysRevert())
{ //user wants to edit
return false; //don't let the editor go away
}
}
return super.stopCellEditing();
}
/**
* Sets integer number format to JFormattedTextField instance,
* sets value of JFormattedTextField instance to object's field value,
* synchronizes object's field value with the value of JFormattedTextField instance.
*
* @param textField JFormattedTextField instance
* @param owner an object whose field is synchronized with {@code textField}
* @param property object's field name for synchronization
*/
public static void setupIntegerFieldTrackingValue(final JFormattedTextField textField,
final InspectionProfileEntry owner,
final String property) {
NumberFormat formatter = NumberFormat.getIntegerInstance();
formatter.setParseIntegerOnly(true);
textField.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(formatter)));
textField.setValue(getPropertyValue(owner, property));
final Document document = textField.getDocument();
document.addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent e) {
try {
textField.commitEdit();
setPropertyValue(owner, property,
((Number) textField.getValue()).intValue());
} catch (ParseException e1) {
// No luck this time
}
}
});
}
/**
* Create a new instance of PurchaseInfoTab
*/
public PurchaseInfoTab()
{
this.availableTable = new FilteredTreeViewTable<>();
this.purchasedTable = new FilteredTreeViewTable<>();
this.equipmentRenderer = new EquipmentRenderer();
this.autoResizeBox = new JCheckBox();
this.addCustomButton = new JButton();
this.addEquipmentButton = new JButton();
this.sellEquipmentButton = new JButton();
this.removeEquipmentButton = new JButton();
this.infoPane = new InfoPane();
this.wealthLabel = new JFormattedTextField(NumberFormat.getNumberInstance());
this.goldField = new JFormattedTextField(NumberFormat.getNumberInstance());
this.goldModField = new JFormattedTextField(NumberFormat.getNumberInstance());
this.buySellRateBox = new JComboBox<>();
this.fundsAddButton = new JButton();
this.fundsSubtractButton = new JButton();
this.allowDebt = new JCheckBox();
this.currencyLabels = new ArrayList<>();
initComponents();
}
/**
* Returns either the default formatter, display formatter, editor
* formatter or null formatter based on the state of the
* JFormattedTextField.
*
* @param source JFormattedTextField requesting
* JFormattedTextField.AbstractFormatter
* @return JFormattedTextField.AbstractFormatter to handle
* formatting duties.
*/
public JFormattedTextField.AbstractFormatter getFormatter(
JFormattedTextField source) {
JFormattedTextField.AbstractFormatter format = null;
if (source == null) {
return null;
}
Object value = source.getValue();
if (value == null) {
format = getNullFormatter();
}
if (format == null) {
if (source.hasFocus()) {
format = getEditFormatter();
}
else {
format = getDisplayFormatter();
}
if (format == null) {
format = getDefaultFormatter();
}
}
return format;
}
/**
* Creates a dialog to change the grid size.
* @param settings are the {@link GameSettings} that will receive the new grid size.
*/
public GridSizeDialog(GameSettings settings) {
this.settings = settings;
widthInput = new JFormattedTextField(createNumberFormatter());
widthInput.setColumns(TEXT_FIELD_COLUMNS);
heightInput = new JFormattedTextField(createNumberFormatter());
heightInput.setColumns(TEXT_FIELD_COLUMNS);
setLayout(new BorderLayout());
add(new JLabel(MESSAGE), BorderLayout.NORTH);
JPanel subPanel = new JPanel();
subPanel.add(new JLabel(WIDTH));
subPanel.add(widthInput);
subPanel.add(Box.createHorizontalStrut(SPACE)); // a spacer
subPanel.add(new JLabel(HEIGHT));
subPanel.add(heightInput);
add(subPanel, BorderLayout.SOUTH);
}
/**
* Returns either the default formatter, display formatter, editor
* formatter or null formatter based on the state of the
* JFormattedTextField.
*
* @param source JFormattedTextField requesting
* JFormattedTextField.AbstractFormatter
* @return JFormattedTextField.AbstractFormatter to handle
* formatting duties.
*/
public JFormattedTextField.AbstractFormatter getFormatter(
JFormattedTextField source) {
JFormattedTextField.AbstractFormatter format = null;
if (source == null) {
return null;
}
Object value = source.getValue();
if (value == null) {
format = getNullFormatter();
}
if (format == null) {
if (source.hasFocus()) {
format = getEditFormatter();
}
else {
format = getDisplayFormatter();
}
if (format == null) {
format = getDefaultFormatter();
}
}
return format;
}
public void setDateFormat( final DateFormat timeFormat ) {
if ( timeFormat == null ) {
throw new NullPointerException();
}
dateField.setFormatterFactory( new JFormattedTextField.AbstractFormatterFactory() {
public JFormattedTextField.AbstractFormatter getFormatter( final JFormattedTextField tf ) {
return new DateFormatter( timeFormat ) {
// allow to clear the field
public Object stringToValue( final String text ) throws ParseException {
return "".equals( text ) ? null : super.stringToValue( text );
}
};
}
} );
if ( timeFormat instanceof SimpleDateFormat ) {
final SimpleDateFormat dateFormat = (SimpleDateFormat) timeFormat;
setToolTipText( dateFormat.toLocalizedPattern() );
} else {
setToolTipText( null );
}
if ( dateChooserPanel != null ) {
setDate( getCellEditorValue() );
}
}
private JSpinner createSpinner(int value)
{
SpinnerModel model = new SpinnerNumberModel(value, Integer.MIN_VALUE, Integer.MAX_VALUE, 1);
JSpinner spinner = new JSpinner(model);
Component editor = spinner.getEditor();
JFormattedTextField spinnerTextField = ((JSpinner.DefaultEditor) editor).getTextField();
spinnerTextField.setColumns(4);
return spinner;
}
private JFormattedTextField createMumberField(List<NumberFormatter> dynamicFormatters) {
final NumberFormatter defaultFormatter = new NumberFormatter(new DecimalFormat(axisBuilder.getFormat()));
final NumberFormatter displayFormatter = new NumberFormatter(new DecimalFormat(axisBuilder.getFormat()));
final NumberFormatter editFormatter = new NumberFormatter(new DecimalFormat());
dynamicFormatters.add(defaultFormatter);
dynamicFormatters.add(displayFormatter);
JFormattedTextField numberField = new JFormattedTextField( //
new DefaultFormatterFactory(defaultFormatter, displayFormatter, editFormatter));
numberField.setColumns(12);
return numberField;
}
public static JFormattedTextField createDateField(JPanel pnl, String str, String tip) {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
JFormattedTextField txt = new JFormattedTextField(format);
txt.setText(str);
txt.setToolTipText(tip);
pnl.add(txt);
return txt;
}
public void focusGained(FocusEvent event) {
Object source = event.getSource();
if (source instanceof JFormattedTextField) {
this.text = (JFormattedTextField) source;
SwingUtilities.invokeLater(this);
}
}
public void focusGained(FocusEvent event) {
Object source = event.getSource();
if (source instanceof JFormattedTextField) {
this.text = (JFormattedTextField) source;
SwingUtilities.invokeLater(this);
}
}
HexaEditor (JSpinner spinner)
{
super(spinner);
JFormattedTextField ftf = getTextField();
ftf.setEditable(true);
ftf.setFormatterFactory(new HexaFormatterFactory());
}
public RangeComponent(NumberFormat format) {
minTxtField = new JFormattedTextField(format);
maxTxtField = new JFormattedTextField(format);
minTxtField.setColumns(TEXTFIELD_COLUMNS);
maxTxtField.setColumns(TEXTFIELD_COLUMNS);
add(minTxtField, 0, 0, 1, 1, 1, 0);
add(new JLabel(" - "), 1, 0, 1, 1, 0, 0);
add(maxTxtField, 2, 0, 1, 1, 1, 0);
}
ColorChooserPanel(ColorModel model) {
this.model = model;
this.panel = new ColorPanel(this.model);
this.slider = new DiagramComponent(this.panel, false);
this.diagram = new DiagramComponent(this.panel, true);
this.text = new JFormattedTextField();
this.label = new JLabel(null, null, SwingConstants.RIGHT);
ValueFormatter.init(6, true, this.text);
}
private Component getNumberInput(Object o) throws Exception {
Object maxValue = parseNumber(o.getClass(), o.getClass().getDeclaredField("MAX_VALUE").get(null).toString());
Object minValue = parseNumber(o.getClass(), o.getClass().getDeclaredField("MIN_VALUE").get(null).toString());
JFormattedTextField numberField = createNumberField(o.getClass(), minValue, maxValue);
numberField.setValue(o);
return numberField;
}
public void focusGained(FocusEvent event) {
Object source = event.getSource();
if (source instanceof JFormattedTextField) {
this.text = (JFormattedTextField) source;
SwingUtilities.invokeLater(this);
}
}
ColorChooserPanel(ColorModel model) {
this.model = model;
this.panel = new ColorPanel(this.model);
this.slider = new DiagramComponent(this.panel, false);
this.diagram = new DiagramComponent(this.panel, true);
this.text = new JFormattedTextField();
this.label = new JLabel(null, null, SwingConstants.RIGHT);
ValueFormatter.init(6, true, this.text);
}
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
private void initContentPanel() {
GridLayout gridLayout = new GridLayout(5, 2, 4, 4);
contentPanel.setLayout(gridLayout);
checkBoxPlayerIsBlack =
new JCheckBox(resourceBundle.getString("NewGameDialog.PlayBlack"), true);
checkBoxPlayerIsBlack.addChangeListener(evt -> togglePlayerIsBlack());
textFieldWhite = new JTextField();
textFieldBlack = new JTextField();
textFieldKomi = new JFormattedTextField(FORMAT_KOMI);
textFieldHandicap = new JFormattedTextField(FORMAT_HANDICAP);
textFieldHandicap.setEnabled(false);
textFieldHandicap.addPropertyChangeListener(evt -> modifyHandicap());
contentPanel.add(checkBoxPlayerIsBlack);
chkNewGame = new JCheckBox(resourceBundle.getString("NewGameDialog.NewGame"), false);
chkNewGame.addChangeListener(evt -> toggleNewGame());
contentPanel.add(chkNewGame);
contentPanel.add(new JLabel(resourceBundle.getString("NewGameDialog.Black")));
contentPanel.add(textFieldBlack);
contentPanel.add(new JLabel(resourceBundle.getString("NewGameDialog.White")));
contentPanel.add(textFieldWhite);
contentPanel.add(new JLabel(resourceBundle.getString("NewGameDialog.Komi")));
contentPanel.add(textFieldKomi);
contentPanel.add(new JLabel(resourceBundle.getString("NewGameDialog.Handicap")));
contentPanel.add(textFieldHandicap);
textFieldKomi.setEnabled(true);
dialogPane.add(contentPanel, BorderLayout.CENTER);
}
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
public void focusGained(FocusEvent event) {
Object source = event.getSource();
if (source instanceof JFormattedTextField) {
this.text = (JFormattedTextField) source;
SwingUtilities.invokeLater(this);
}
}
public MarvinMatrixPanel(int rows, int columns){
this.rows = rows;
this.columns = columns;
JPanel panelTextFields = new JPanel();
GridLayout layout = new GridLayout(rows, columns);
panelTextFields.setLayout(layout);
//Format
DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols dfs = decimalFormat.getDecimalFormatSymbols();
dfs.setDecimalSeparator('.');
decimalFormat.setDecimalFormatSymbols(dfs);
textFields = new JFormattedTextField[rows][columns];
for(int r=0; r<rows; r++){
for(int c=0; c<columns; c++){
textFields[r][c] = new JFormattedTextField(decimalFormat);
textFields[r][c].setValue(0.0);
textFields[r][c].setColumns(4);
panelTextFields.add(textFields[r][c]);
}
}
setLayout(new FlowLayout(FlowLayout.CENTER));
add(panelTextFields);
}
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
public JFormattedTextField getSpamMessageAmountThreshold_() {
return spamMessageAmountThreshold_;
}
private void checkNonNegative(JFormattedTextField field, int defaultValue) {
if (((Number)field.getValue()).intValue() < 0)
field.setValue(defaultValue);
}
@Override
public void run() {
runTest(new Panel());
runTest(new Button());
runTest(new Checkbox());
runTest(new Canvas());
runTest(new Choice());
runTest(new Label());
runTest(new Scrollbar());
runTest(new TextArea());
runTest(new TextField());
runTest(new Dialog(new JFrame()));
runTest(new Frame());
runTest(new Window(new JFrame()));
runTest(new FileDialog(new JFrame()));
runTest(new List());
runTest(new ScrollPane());
runTest(new JFrame());
runTest(new JDialog(new JFrame()));
runTest(new JWindow(new JFrame()));
runTest(new JLabel("hi"));
runTest(new JMenu());
runTest(new JTree());
runTest(new JTable());
runTest(new JMenuItem());
runTest(new JCheckBoxMenuItem());
runTest(new JToggleButton());
runTest(new JSpinner());
runTest(new JSlider());
runTest(Box.createVerticalBox());
runTest(Box.createHorizontalBox());
runTest(new JTextField());
runTest(new JTextArea());
runTest(new JTextPane());
runTest(new JPasswordField());
runTest(new JFormattedTextField());
runTest(new JEditorPane());
runTest(new JButton());
runTest(new JColorChooser());
runTest(new JFileChooser());
runTest(new JCheckBox());
runTest(new JInternalFrame());
runTest(new JDesktopPane());
runTest(new JTableHeader());
runTest(new JLayeredPane());
runTest(new JRootPane());
runTest(new JMenuBar());
runTest(new JOptionPane());
runTest(new JRadioButton());
runTest(new JRadioButtonMenuItem());
runTest(new JPopupMenu());
//runTest(new JScrollBar()); --> don't test defines max and min in
// terms of preferred
runTest(new JScrollPane());
runTest(new JViewport());
runTest(new JSplitPane());
runTest(new JTabbedPane());
runTest(new JToolBar());
runTest(new JSeparator());
runTest(new JProgressBar());
if (!failures.isEmpty()) {
System.out.println("These classes failed");
for (final Component failure : failures) {
System.out.println(failure.getClass());
}
throw new RuntimeException("Test failed");
}
}
/**
* @return the maxSlowSearchTime_
*/
public JFormattedTextField getMaxSlowSearchTime_() {
return maxSlowSearchTime_;
}