两个问题合二为一,但我有一个非常简短的测试用例来证明我的问题:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.imageio.*;
public class Numbers {
public static void main(String[] args) throws IOException {
double[] numbers = { 10000.12, 20000.23, 3000.45 };
DecimalFormat format = new DecimalFormat("0.00");
format.setGroupingUsed(false);
BufferedImage image = new BufferedImage(400, 150, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.BLACK);
g2d.setBackground(Color.YELLOW);
g2d.clearRect(0, 0, image.getWidth(), image.getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(new Font(Font.SANS_SERIF,Font.BOLD, 24));
FontMetrics metrics = g2d.getFontMetrics();
for (int i = 0; i < numbers.length; i++) {
String str = format.format(numbers[i]);
System.out.println(i + ": " + str);
int w = metrics.stringWidth(str);
int h = metrics.getHeight();
int x = 100 * i;
g2d.drawString(str, x - w/2, 0);
}
g2d.dispose();
ImageIO.write(image, "PNG", new File("Numbers.png"));
}
}
当我使用它时,我得到:
C:\Temp>javac -version
javac 1.6.0_24
C:\Temp>javac Numbers.java
C:\Temp>java Numbers
0: 10000,12
1: 20000,23
2: 3000,45
这张图片产生了:
我的问题:
- 如何在不切换语言环境的情况下强制 DecimalFormat 使用点而不是逗号?
- w 似乎是正确的,但是 0 作为高度有什么问题 - 为什么数字会打印在屏幕外?
谢谢!亚历克斯
更新:
我最终使用了语言环境。str.replace(".", ",") 注释也很酷。
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.imageio.*;
public class Numbers {
public static void main(String[] args) throws IOException {
double[] numbers = { 10000.12, 20000.23, 3000.45 };
BufferedImage image = new BufferedImage(400, 150, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE);
g2d.setBackground(Color.GRAY);
g2d.clearRect(0, 0, image.getWidth(), image.getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(new Font(Font.SANS_SERIF,Font.BOLD, 24));
FontMetrics metrics = g2d.getFontMetrics();
NumberFormat format = NumberFormat.getInstance(Locale.US);
format.setGroupingUsed(false);
if (format instanceof DecimalFormat) {
((DecimalFormat) format).applyPattern("0.00");
}
for (int i = 0; i < numbers.length; i++) {
String str = format.format(numbers[i]);
System.out.println(i + ": " + str);
int w = metrics.stringWidth(str);
int h = metrics.getHeight();
int x = 100 * i;
g2d.drawString(str, x - w/2, h);
}
g2d.dispose();
ImageIO.write(image, "PNG", new File("Numbers.png"));
}
}