Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

public class Main extends JPanel implements PropertyChangeListener {
    double amount = 100000;
    JFormattedTextField amountField;

    NumberFormat amountDisplayFormat;
    NumberFormat amountEditFormat;

    public Main() {
        super(new BorderLayout());
        amountDisplayFormat = NumberFormat.getCurrencyInstance();
        System.out.println(amountDisplayFormat.format(1200));
        amountDisplayFormat.setMinimumFractionDigits(0);
        amountEditFormat = NumberFormat.getNumberInstance();
        amountField = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(amountDisplayFormat),
                new NumberFormatter(amountDisplayFormat), new NumberFormatter(amountEditFormat)));
        amountField.setValue(new Double(amount));
        amountField.setColumns(10);
        amountField.addPropertyChangeListener("value", this);

        JPanel fieldPane = new JPanel(new GridLayout(0, 1));
        fieldPane.add(amountField);

        add(fieldPane, BorderLayout.LINE_END);
        add(new JButton("Hello"), BorderLayout.SOUTH);
    }

    public void propertyChange(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == amountField) {
            amount = ((Number) amountField.getValue()).doubleValue();
            System.out.println("amount = " + amount);
            amountField.setValue(amount);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("FormatDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new Main());
        frame.pack();
        frame.setVisible(true);
    }
}