package com.javamarcher.window;
import java.util.Locale;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import com.javamarcher.util.ActionGeneric;
public class DoubleJTextfieldWithLabel extends LabelBasedUIComponent {
private final ActionGeneric<Double> updateAction;
public DoubleJTextfieldWithLabel(String label, double startValue, ActionGeneric<Double> updateAction, int commaDigitCount, int columnWidth) {
super(label);
this.updateAction = updateAction;
final JTextField textField = new JTextField(String.format(Locale.US, "%." + commaDigitCount + "f", startValue), columnWidth);
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateValue(e.getDocument());
}
@Override
public void insertUpdate(DocumentEvent e) {
updateValue(e.getDocument());
}
@Override
public void changedUpdate(DocumentEvent e) {
// Nothing to do here.
}
});
addComponentToContainer(textField);
}
/**
* Updates the textfield String data if possible.
* Should be called if the textfield is altered.
*/
private void updateValue(Document document) {
String textfieldString = null;
try {
textfieldString = document.getText(0, document.getEndPosition().getOffset());
} catch (BadLocationException e) {
System.err.println(e.toString());
}
// Update value only if string is a valid double
if(textfieldString != null) {
try {
final double parsedTextData = Double.parseDouble(textfieldString);
// Trigger update action
updateAction.performAction(parsedTextData);
} catch(NumberFormatException e) {
// Nothing to do here
}
}
}
}