MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class MainClass {

    public static JPanel demo1() {
        JPanel pan = new JPanel(new BorderLayout());
        pan.setBorder(new TitledBorder("change format midstream"));

        MaskFormatter lowercase = null;
        try {
            lowercase = new MaskFormatter("LLLL");
        } catch (ParseException pe) {
        }
        final JFormattedTextField field = new JFormattedTextField(lowercase);
        field.setValue("lower case");
        pan.add(field, BorderLayout.CENTER);

        final JButton change = new JButton("change format");
        JPanel changePanel = new JPanel();
        changePanel.add(change);
        pan.add(changePanel, BorderLayout.SOUTH);

        change.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                try {
                    field.commitEdit();
                    MaskFormatter uppercase = new MaskFormatter("UUUU");
                    DefaultFormatterFactory factory = new DefaultFormatterFactory(uppercase);
                    field.setFormatterFactory(factory);
                    change.setEnabled(false);
                } catch (ParseException pe) {
                }
            }
        });

        return pan;
    }

    public static void main(String argv[]) {
        JFrame f = new JFrame("FactoryDemo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(demo1(), BorderLayout.NORTH);
        f.getContentPane().add(new JTextField(), BorderLayout.SOUTH);
        f.setSize(240, 160);
        f.setVisible(true);
    }
}