platypus
platypus

Reputation: 706

Specifying the input

Is there any way to force a user to give his/her input via overwriting certain characters.

i.e.:

First screen:

Amount: ___.__

Second:

Amount: 1__.__

... goes like this ...

Finally:

Amount: 1200.50

But i want to be sure that numbers will be printed as soon as user presses the keyboard.

Thanks in advance.

p.s.: OS is MS Windows 9x/XP/Vista/7. And the application is for console.

Upvotes: 0

Views: 91

Answers (2)

Bala R
Bala R

Reputation: 108947

MaskFormatter mf1 = new MaskFormatter("#####.##");
mf1.setPlaceholderCharacter('_');
JFormattedTextField ftf1 = new JFormattedTextField(mf1);

Here's the full code

import java.awt.Container;
import java.text.ParseException;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;

public class Test {

    public static void main(String args[]) throws ParseException {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = f.getContentPane();
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

        MaskFormatter mf1 = new MaskFormatter("######.###");
        mf1.setPlaceholderCharacter('_');
        JFormattedTextField ftf1 = new JFormattedTextField(mf1);
        content.add(ftf1);

        f.setSize(300, 100);
        f.setVisible(true);
    }

}

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272257

You don't say what OS you're on. For performing advanced input terminal work, this could be important.

You could spend some time implementing such a solution in Java by capturing keystrokes yourself, regenerating the input line etc. On the other hand, have you looked at JLine ?

Upvotes: 2

Related Questions