Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {
    JFormattedTextField jft;
    JButton jb = new JButton("but");

    public Main() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel jl = new JLabel("Try with formatted text field   ");
        Locale local1 = new Locale("en", "US");
        int minFra = 0;
        int maxFra = 3;
        jft = setFormat(jft, local1, minFra, maxFra);
        jft.setMaximumSize(new Dimension(100, 20));
        jft.setMinimumSize(new Dimension(100, 20));
        jft.setPreferredSize(new Dimension(100, 20));

        frame.add(jl);
        frame.add(jft, BorderLayout.NORTH);
        jb.addActionListener(e -> JOptionPane.showMessageDialog(jb, "nel text Box : " + jft.getText()));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

    private JFormattedTextField setFormat(JFormattedTextField jft, Locale local1, int minFra, int maxFra) {
        NumberFormat numberFormat;
        Locale local = local1;
        int setMin = minFra;
        int setMax = maxFra;
        numberFormat = NumberFormat.getCurrencyInstance(local);
        numberFormat.setMinimumFractionDigits(setMin);
        numberFormat.setMaximumFractionDigits(setMax);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);
        jft = new JFormattedTextField(numberFormat);
        jft.setValue(new Double(342.796));
        return jft;
    }
}