Custom JFormattedTextField Format

I need to make a JFormattedTextField in accordance with the "00:00" format with some requirements:

  • The only value to be changed must be either "00". (So ​​":" should not be deleted)
  • The tab allows you to switch between the two sides ":". (Thus, having the cursor on one side and tabs as “00” on the other side)
  • Changing “00” to “2” should format it to “02”.
  • The limit of its symbol must be 5, including ":". (4 changeable characters)
  • It should be initialized as "00:00", but it should not be acceptable.
  • You must not enter anything other than numbers. (Letters, characters, negative numbers, etc.)

Is there any way to do this? I looked at various formatting elements, validators, and a document filter to add to the JFormattedTextField, but I'm not sure who to go with. (Using DefaultFormatter right now, but looked at NumberFormatter for a limitation. Do I need to use a combination of formatter and validator?)

This is my JFormattedTextField right now: http://pastebin.com/jW2RSJXe[1].

Any of the code that does this with examples / pointers to what to see will be appreciated!

+4
source share
1 answer

. MaskFormatter. : , , , , 2, 02. .

import java.awt.BorderLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class MaskFormatterTest extends JPanel {

    private JFormattedTextField formatText;

    public MaskFormatterTest() {
        formatText = new JFormattedTextField(createFormatter("##:##"));
        formatText.setColumns(20);
        formatText.setText("00:00");

        setLayout(new BorderLayout());
        add(new JLabel("Enter only numbers"), BorderLayout.NORTH);
        add(formatText, BorderLayout.CENTER);
    }

    private MaskFormatter createFormatter(String s) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(s);
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("MaskFormatter example");
                frame.add(new MaskFormatterTest());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationByPlatform(true);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

MaskFormatter . ##:##. , .

: formatText.setText("00:00"); .

+2

All Articles