I'm trying to create a field to take measurements, I wanted to apply a mask so that it would look like this:
Thefieldalreadystartswith0.00,thenifyouentervalueitwillkeeptheformatting.
AndwhenIputthevaluesbackinthefield,itdidnotlosetheformatting.
Itriedsomethingslikethisbefore: link
but the result is different than I expected. I tried to rely on monetary fields taken from the internet, but I did not succeed either.
What I did:
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import static javax.swing.SwingConstants.RIGHT;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;
public class Main extends JFrame {
private JPanel jpn = new JPanel();
private Medida medida = new Medida();
public Main() {
jpn.add(medida);
add(jpn);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String arg[]) {
new Main().setVisible(true);
}
}
class Medida extends JFormattedTextField implements CaretListener {
public Medida() {
setColumns(5);
this.setDocument(new MeuDocument(4));
setHorizontalAlignment(RIGHT);
addCaretListener(this);
setText("0,00");
getCaret().setDot(getText().length());
}
@Override
public void caretUpdate(CaretEvent e) {
if (getCaret().getMark() != getText().length()) {
getCaret().setDot(getText().length());
}
}
public BigDecimal getValor() {
return new BigDecimal(getText().replace(".", "").replace(",", "."));
}
public void setValor(BigDecimal valor) {
setText(valor.toString());
}
class MeuDocument extends PlainDocument {
private Integer tamanho;
public MeuDocument(int tamanho) {
this.tamanho = tamanho + 1; //tem que contar o separador de decimal (,)
}
@Override
public void insertString(int offs, String str, AttributeSet a) {
try {
Pattern padrao = Pattern.compile("[0123456789]");
Matcher matcher = padrao.matcher(str);
String valorAtual = getText(0, getLength()).trim().replace(".", "").replace(",", "");
str = str.trim().replace(",", ".");
/*NumberFormat nf = NumberFormat.getCurrencyInstance();
String valorFormatado = nf.format(valor).replace("R$ ", "");
StringBuffer strBuf = new StringBuffer(valorFormatado);
valorFormatado = valorFormatado.replace(".", "").replace(",", "").replace("-", ""); //retira tudo o que não for dígito para poder verificar o tamanho.
if ((tamanho != null) && (valorFormatado.length() >= tamanho)) {
return;
}
super.remove(0, getLength());
super.insertString(0, strBuf.toString(), a);*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
}