I’m currently writing a calendar / date picker implementation and I was wondering if anyone knows of a faster / easier way to achieve the following effect.
eg.
05/02/2012 - 11/02/2012
The effect I’m after is for the dividers (/) to always remain in the same place, and for the values to always fit in between them. This makes it much easier to follow when you’re scrolling through weeks, because the font is not monospace.
The way I’m currently doing it seems over the top but it works.
I’m optimizing / refactoring and came across it thinking there must be a better way to do it.
Here’s what I have:
//getText() return a range in the format dd/mm/yyyy - dd/mm/yyyy
String firstHalf = getText().substring(0, 10);
String secondHalf = getText().substring(getText().length() - 10);
int yOff = baseLine - ((showSubtext) ? 5 : 0);
int slashWidth = fm.stringWidth("/");
String a, b, c, d, e, f;
int A, B, C, D, ax, bx, cx, dx, ex, fx;
a = firstHalf.substring(0, 2);
b = firstHalf.substring(3, 5);
c = firstHalf.substring(6);
d = secondHalf.substring(0, 2);
e = secondHalf.substring(3, 5);
f = secondHalf.substring(6);
int sideGap = 45;
int fieldWidth = 28;
int leftOffset = 4;
A = sideGap + fieldWidth;
B = A + fieldWidth + slashWidth / 2;
D = getWidth() - A - 20;
C = D - fieldWidth - slashWidth / 2;
ax = A - fm.stringWidth(a);
bx = ((B - A) - fm.stringWidth(b)) / 2 + A + slashWidth / 2 + 1;
cx = B + slashWidth;
dx = C - fm.stringWidth(d);
ex = ((D - C) - fm.stringWidth(e)) / 2 + C + slashWidth / 2 + 1;
fx = D + slashWidth;
g.drawString("/", A - leftOffset, yOff);
g.drawString("/", B - leftOffset, yOff);
g.drawString("/", C, yOff);
g.drawString("/", D, yOff);
g.drawString(a, ax - leftOffset, yOff);
g.drawString(b, bx - leftOffset, yOff);
g.drawString(c, cx - leftOffset, yOff);
g.drawString(d, dx, yOff);
g.drawString(e, ex, yOff);
g.drawString(f, fx, yOff);
Effect:

Thanks.
Even proportionally spaced fonts typically give the digit glyphs a constant advance. The UI default or the actual
Fontfor a given logical family are fairly reliable. As @Hovercraft comments, you can then leverage all the considerable benefits ofSimpleDateFormat.