All Downloads are FREE. Search and download functionalities are using the official Maven repository.

convex.gui.components.DecimalAmountField Maven / Gradle / Ivy

package convex.gui.components;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;

import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

import convex.core.data.prim.AInteger;
import convex.core.text.Text;

/**
 * Component displaying a decimal quantity in an editable text field, constrained to a decimal with a maximum number of digits
 */
@SuppressWarnings("serial")
public class DecimalAmountField extends JTextField {
	
	protected final int decimals;

	public DecimalAmountField(int decimals) {
		super("0");
		this.decimals=decimals;
		this.setHorizontalAlignment(SwingConstants.RIGHT);
		//setColumns(10+decimals);
	}
	
	public static DecimalFormat getNumberFormat(int decimals) {
		DecimalFormat df= new DecimalFormat("#,###"+((decimals>0)?("."+Text.repeat('#',decimals)):""));
		return df;
	}
	
	@Override 
	protected Document createDefaultModel() {
		return new DecimalDocument();
	}
	
	@Override
	public Dimension getPreferredSize() {
		Dimension d=super.getPreferredSize();
		FontMetrics font=getFontMetrics(getFont());
		int pw=font.charWidth('0')*(10+decimals);
		if (d.width=0) {
					super.remove(dotPos,tlen-dotPos);
					offset=dotPos;
				} else {
					offset=tlen;
					dotPos=0;
				}
			}
			// suppress digits after decimal length
			if ((dotPos>=0)) {
				int digits=(offset+n-dotPos)-1;
				if (digits>decimals) {
					n=n-digits+decimals;
				}
			}

			// String to insert
			String insertS=new String(newChars);
			if (n0) {
				dec=dec.multiply(new BigDecimal(BigInteger.TEN.pow(decimals)));
			}
			BigInteger bi=(exact?dec.toBigIntegerExact():dec.toBigInteger());
			return AInteger.create(bi);
		} catch (NumberFormatException e) {
			return null;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
 }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy