/** * Gets the displayed value, and uses the converter to convert the shared value to units this * instance is supposed to represent. If the displayed value and shared value are different, * then we turn off our document filter and update our value to match the shared value. We * re-enable the document filter afterwards. */ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); try { StyledDocument doc = getStyledDocument(); double actualValue = (multiplier.getDisplayValue(value.getValue())); String actualValueAsString = df.format(actualValue); String displayedValue; try { displayedValue = doc.getText(0, doc.getLength()); } catch (BadLocationException e) { displayedValue = ""; } if (displayedValue.isEmpty()) { displayedValue = "0"; } double displayedValueAsDouble = Double.parseDouble(displayedValue); if (!actualValueAsString.equals(displayedValue) && displayedValueAsDouble != actualValue) // Allow user to enter trailing zeroes. { bypassFilterAndSetText(doc, actualValueAsString); } } catch (NumberFormatException e) { // Swallow it as it's OK for the user to try and enter non-numbers. } }
protected void bypassFilterAndSetText(StyledDocument doc, String text) { try { filter.setUpdateValue(false); doc.remove(0, doc.getLength()); doc.insertString(0, text, null); } catch (BadLocationException e) { java.awt.Toolkit.getDefaultToolkit().beep(); } finally { filter.setUpdateValue(true); } }