I'm trying to create a "weight" field, but I'm having some problems.
Weight can range from 2 to 3 decimal places before the point. For example, it could be 80.00 kg or 100.00 kg. However, in the way I'm doing, it forces me to put the 3 houses before the point.
I also tried putting a setText("00.00");
to the field not "start" just with the point, plus it did not catch. How can I resolve this?
public class Peso extends JFrame {
public static void main(String[] args) {
Peso t = new Peso();
t.setVisible(true);
}
CampoPeso peso = new CampoPeso();
JPanel painel = new JPanel();
public Peso() {
JLabel label = new JLabel("Peso:");
painel.add(label);
painel.add(peso);
add(painel);
setSize(220, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class CampoPeso extends JFormattedTextField {
public CampoPeso() {
setColumns(5);
setText("00.00");
try {
MaskFormatter mf = new MaskFormatter("###.##");
mf.install(this);
} catch (Exception e) {
e.printStackTrace();
}
}
//para pegar o valor
public Float getValor() {
return new Float(getText().replace(".", "").replace(",", "."));
}
//setar o valor
public void setValor(Object valor) {
setText(valor.toString());
}
}