TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
做ERP或财务软件的朋友知道,中国式的凭证录入界面需要一些特殊的显示效果:录入金额的单元格要显示一些数字分割线。估计这个风格来自老式的手工记账本,因为我还隐约的记得当年从生产队仓库里面偷来的账本就是这个样子滴。为了继续与“Swing很丑”的偏见做斗争,持续弘扬java的创新精神,以及“活到老学到老”、天行健程序员天天练习不息、“除了老婆一切都可共享”的做人原则,这里特意用Swing写了一个小例子,实现“中国式”的凭证录入界面,供大伙消遣。
这里面主要用到了Swing Table的Renderer和Editor这两个机制,也是Swing比较有代表性的技术,大家都不陌生。对于熟悉这个机制的童鞋来说,本文实在没什么新意。这里也就不�嗦废话了,直奔主题,点到为止,然后上代码。
用下面代码设置table一个列的renderer和editor:
table.getColumnModel().getColumn(2).setCellRenderer(new MoneyRenderer());
table.getColumnModel().getColumn(2).setCellEditor(new MoneyEditor());
[/code]
在renderer中,首先paint纵向的竖线,然后在paint正常的单元格内容。
@Override
public void paintChildren(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
painter.paint(this, g2d, null);
super.paintComponent(g);
}
[/code]
其中,painter是一个封装好的用来画竖线的类。里面说道:
public class LinePainter {
private Stroke normalStroke = new BasicStroke(1);
private Stroke thickStroke = new BasicStroke(1);
private Color normalColor = Color.lightGray;
private Color tickColor = Color.cyan.darker();
private Color decimalColor = Color.red;
public void paint(JComponent component, Graphics2D g, Color lineColor) {
g.setColor(Color.gray);
g.setFont(component.getFont());
Rectangle2D bounds = g.getFontMetrics().getStringBounds("0", g);
int unitWidth = (int) bounds.getWidth();
int x = component.getWidth();
int rightGap = 0;
if (component.getInsets() != null) {
rightGap = component.getInsets().right;
}
if (component.getBorder() != null) {
rightGap = rightGap + component.getBorder().getBorderInsets(component).right;
}
if (component instanceof JTextComponent) {
JTextComponent textComponent = (JTextComponent) component;
Insets insets = textComponent.getMargin();
rightGap = rightGap + insets.right;
rightGap = rightGap + 2;
}
x = x - rightGap;
int index = 0;
while (x > unitWidth * 2) {
x = x - unitWidth;
if (index == 1) {
g.setStroke(thickStroke);
g.setColor(decimalColor);
} else {
if ((index - 1) % 3 == 0) {
g.setColor(tickColor);
} else {
g.setColor(normalColor);
}
g.setStroke(normalStroke);
}
g.drawLine(x, 0, x, component.getHeight());
index++;
}
if (lineColor != null) {
g.setColor(lineColor);
g.setStroke(this.normalStroke);
g.drawLine(0, component.getHeight() - 1, component.getWidth(), component.getHeight() - 1);
}
}
}
[/code]
很简单,就一个paint函数,画纵向的彩条线而已。注意间距、字体等的考虑。
为了在编辑期间也能显示纵向线条,所以要定制editor,且重写TextField的paint,先画线条,再super正常的内容paint:
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
painter.paint(this, g2d, Color.red);
super.paint(g);
}
[/code]
这样,整个程序就结束了。稍作修改,加上输入格式检查、汇率转换等东西,相信可以很容易的用在你家的ERP或者财务软件上。
俺知道这个程序可能会被扁“没技术含量”。因此给大伙扯点别的,给几个家庭作业,欢迎大家踊跃回答:
这张凭证记录了什么业务活动的发生?
为什么“库存商品”一栏的金额在“借方”,而“银行现金”一栏的金额在“贷方”?
为什么“进项税额”的金额是17.00元?
这里哪些科目到月底需要结转?
如果能轻松回答这几个家庭作业,说明你不仅仅是个优秀的程序员,还是个优秀的财务,嗯,至少做个出纳没问题吧!等咱写不动程序了,去工厂应聘一下出纳,不也能混口饭吃么?!COOOL
源码下载:http://file.javaxxz.com/2014/11/7/235701500.zip |
|