我有一个像军事游戏一样的游戏,并且顶部有一个指示时间的栏。(示例)当凌晨4:06时,它说4:6有一种方法可以将其更改为04:06,但是还要说(示例)11:45,而不是011:045。
这是时间课程:
public class Hud {
public int x, y;
public int money = 1000;
public int reputation = 5;
public int wifi = 3;
public int time = 0;
public int timer = 10;
public int minute = 50;
public int hour = 10;
public Hud(int x, int y) {
this.x = x;
this.y = y;
}
public void tick() {
if (time >= timer) {
time = 0;
minute++;
} else if (time <= timer) {
time++;
}
if (minute >= 60) {
minute = 0;
hour++;
}
if (hour >= 24) {
hour = 0;
}
}
public void render(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2.setRenderingHints(rh);
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, Comp.size.width + 9, 20);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, Comp.size.width + 9, 20);
// money
g.setColor(Color.yellow);
g.setFont(new Font("italic", Font.BOLD, 15));
g.drawString("€ " + money, 10, 17);
// reputation
g.setColor(Color.black);
g.setFont(new Font("italic", Font.BOLD, 15));
g.drawString("Rep: " + reputation, 100, 16);
// time
g.setColor(Color.black);
g.setFont(new Font("italic", Font.BOLD, 15));
g.drawString("" + hour + ":" + minute, Comp.size.width / 2 - 20, 16);
}
}
这与字体绝对无关(所以我不确定为什么在问题标题中提到字体),而与数字格式有关。您可以执行以下操作:
String displayString = String.format("%02d:%02d", minutes, seconds);
这是将以分钟和秒为单位的int格式化为两位数的字符串,如果int只有一位数字长,则以“ 0”开头。
该"%02d"
是格式说明字符串帮助的String.format或java.util.Formatter中知道你是怎么想格式化数字。该%
通知格式,这是一个格式说明。02
表示使其宽2位数,并0
在需要时添加a。d
表示这是一个十进制数字。
例如,
g.setColor(Color.black);
g.setFont(new Font("italic", Font.BOLD, 15));
String displayString = String.format("%02d:%02d", hour, minute);
g.drawString(displayString, Comp.size.width / 2 - 20, 16);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句