Java Swing Tooltip createNumericInput(final String tooltip)

Here you can find the source of createNumericInput(final String tooltip)

Description

creates a JTextField.

License

Open Source License

Parameter

Parameter Description
tooltip the tooltip is shown when the mouse cursor is over the input field

Return

the JTextField

Declaration

@SuppressWarnings("serial")
public static JTextField createNumericInput(final String tooltip) 

Method Source Code

//package com.java2s;
/*//from   w w w. ja  v a2s .co  m
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.Toolkit;

import java.text.NumberFormat;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class Main {
    /**
     * creates a JTextField. it allows only numeric input.
     *
     * @param tooltip the tooltip is shown when the mouse cursor is over the input field
     * @return the JTextField
     */
    @SuppressWarnings("serial")
    public static JTextField createNumericInput(final String tooltip) {
        NumberFormat integerFormat = NumberFormat.getIntegerInstance();
        integerFormat.setGroupingUsed(false);
        integerFormat.setParseIntegerOnly(true);
        final JTextField urlInput = new JTextField();
        urlInput.setToolTipText(tooltip);
        urlInput.setDocument(new PlainDocument() {
            @Override
            public void insertString(final int offset, final String input, final AttributeSet a)
                    throws BadLocationException {
                final String filtered = input.replaceAll("\\D", "");
                if (!filtered.equals(input)) {
                    Toolkit.getDefaultToolkit().beep();
                }
                super.insertString(offset, filtered, a);
            }
        });
        return urlInput;
    }
}

Related

  1. addClickTipEffect(final JComponent component)
  2. createMarker(int span, String tooltip)
  3. displayTooltip(JComponent component)
  4. hideToolTip(JComponent c)
  5. performMultipleReplacements(final Document theDocument, final String theRegexToSearch, final String theReplacement)
  6. setLongerTooltips()