somebody can help me...

Dani AI

Generated

Thread context: original report from with suggestions from (KeyListener), (watch out for paste), (questions about extra dots and navigation keys) and (JFormattedTextField). Key points missing from the replies: KeyListener is fragile (it misses paste/programmatic changes), navigation/backspace handling, and an easy, robust solution is to filter the Document itself.

A DocumentFilter applied to the JTextField's Document enforces rules at the model level, so typing, clipboard paste, drag/drop and programmatic updates are all covered. The short example below allows only digits and a single dot, accepts a leading dot (".5"), and optionally limits decimal places (-1 = unlimited).

import javax.swing.text.*;

public class NumericDotFilter extends DocumentFilter {
    private final int maxDecimals; // -1 = unlimited

    public NumericDotFilter(int maxDecimals) { this.maxDecimals = maxDecimals; }

    private boolean isValid(String text) {
        if (text == null || text.isEmpty()) return true;
        int dotIndex = -1, dotCount = 0;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == '.') {
                dotCount++; if (dotCount > 1) return false;
                dotIndex = i;
            } else if (!Character.isDigit(c)) {
                return false;
            }
        }
        if (maxDecimals >= 0 && dotIndex >= 0) {
            int decimals = text.length() - dotIndex - 1;
            if (decimals > maxDecimals) return false;
        }
        return true;
    }

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, string);
        if (isValid(sb.toString())) super.insertString(fb, offset, string, attr);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(offset, offset + length, text == null ? "" : text);
        if (isValid(sb.toString())) super.replace(fb, offset, length, text, attrs);
    }
}

Attach to a field like this:

JTextField tf = new JTextField(10);
((AbstractDocument)tf.getDocument()).setDocumentFilter(new NumericDotFilter(2)); // 2 decimal places

Notes and cautions: DocumentFilter preserves backspace, delete and arrow-key navigation (addresses ). It also prevents pasted invalid text (addresses ). The JFormattedTextField route (mentioned by ) is a good alternative when locale-aware formatting and parsing are needed; DocumentFilter gives finer, immediate control for simple character restrictions. Always validate/parsethe final value before using it (defensive check) and adjust the filter if negatives or a different decimal separator (locale comma) are required.

Recommended Answers

All 5 Replies

this is only a school assignment,,, but i cant find a way how to solve it.

with a key listener, for instance. you add a key listener that checks the input given, if it's not a number or a ., have it consume the event.

In addition to the above, be sure to check input again before sending the actual input data. There are users who, when they can't type what they want, will copy-paste their garbage input (with the mouse obviously, how could they ever press two keys at once, that's just madness). Then when they don't get a result they'll call you in the middle of the night (because that's when "you guys" work right) telling you to come fix their mouse, because the "mouse inputs" are not getting results.

<heavy breathing>

Are you going to allow more than one . input?
How about backspace and left right keys?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.