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 IntJTextfieldWithLabel extends LabelBasedUIComponent { private final ActionGeneric<Integer> updateAction; public IntJTextfieldWithLabel(String label, int startValue, ActionGeneric<Integer> updateAction, int columnWidth) { super(label); this.updateAction = updateAction; final JTextField textField = new JTextField(String.format(Locale.US, "%d", 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 int parsedTextData = Integer.parseInt(textfieldString); // Trigger update action System.out.println("30"); updateAction.performAction(parsedTextData); } catch(NumberFormatException e) { // Nothing to do here } } } }