/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.components.textfield;

import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import java.text.ParseException;

public class FormattedTextFieldExample extends JPanel {
	public FormattedTextFieldExample() throws ParseException {
		super(new FlowLayout());

		final NumberFormat numberFormat = NumberFormat.getPercentInstance();
		numberFormat.setMaximumFractionDigits(2);
		numberFormat.setMinimumFractionDigits(2);

		final JFormattedTextField textField = new JFormattedTextField(numberFormat);
		textField.setValue(0.35);
		textField.setColumns(10);
		textField.setEditable(true);

		textField.addPropertyChangeListener("value", new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
				System.out.println(textField.getValue() + " vs. " + textField.getText());
			}
		});

		// 레이아웃에 추가
		add(textField);

		final MaskFormatter maskFormatter = new MaskFormatter("###-####-####");
		final JFormattedTextField textField2 = new JFormattedTextField(maskFormatter);

		add(textField2);
	}

	public static void main(String... args) throws ParseException {

		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new FormattedTextFieldExample());

		SwingUtilities.invokeLater(() -> {
			jFrame.setVisible(true);
		});


	}
}
